views:

44

answers:

1

I'm reading about the State pattern. I have only just begun, so of course I begin by reading the entire Wikipedia article on it.

I noticed that both of the examples in the article have some base abstract class or Java interface for a generic State's methods/functions. Then there are some states which inherit from the base and implement those methods/functions in different ways. Then there's a Context class which has a private member of type State and which, at any time, can be equal to an instance of one of the implementations. That context class also implements the same methods, and passes them onto the current state instance, and then has an additional method to change the state (or depending on design I understand the change of state could be a reaction to one of the implemented methods).

Why doesn't this context class specifically "extend" or "implement" the generic State base class/interface?

+3  A: 

Because the state is an implementation detail, not part of its interface. I.e. the Context is not a State, it only has a State. Users of the Context need not even be aware of it having a state.

Péter Török
Sounds good. It's purely conceptual. Definitely makes sense, and I had this sort of feeling but I guess I just needed to hear it from someone else. :)
Ricket
@Ricket, one further note: although the Wikipedia examples show the Context having the same interface as State, IMO this is not an inherent part of the pattern - the interfaces might be slightly or even completely different.
Péter Török
@Ricket, there is a practical benefit too - the `Context` interface can be simpler than the `State` interface (as in the State/StateContext example).
Jeff Sternal