|
Context: defines the interface of interest to
clients and maintains an instance of a ConcreteState that
defines the current state.
State: defines an interface for
encapsulating the behavior associated with a particular
state of the Context.
ConcreteState subclasses: implement
a behavior associated with a state of the Context.
Context delegates all state-specific
request to the correspondent ConcreteState object.
Whenever the state in the Context changes, the
ConcreteState object is changed accordingly. Either
Context or the ConcreteState subclasses can decide which
state succeeds another and under what circumstances.
The State pattern has the following
consequences:
It
localizes state-specific behavior and partitions behavior
for different states. Because all state-specific code is
implemented in a ConcreteState class, new states and
transition can be added easily by defining new subclasses
of the State class. Besides, State pattern eliminates
large conditional statements necessary for many states,
imposing a structure on the code that makes its intent
clearer.
It makes state transitions explicit.
Introducing separate objects of different states makes
the transitions more explicit than in the case of the
implementation with conditional statements.
State objects can be shared.
Contexts can share a State object, if State objects have
no instance variables.
[ The information provided above is
partially or fully obtained from this book, which is reproduced
here for reference only. ]
[ Back
to Knowledge base ]
|