Java Reference
In-Depth Information
The current state of the door makes it behave differently in response to the same command.
Implementation
Figure 2.12. State class diagram
Implementing the State pattern requires:
Context -
Keeps a reference to the current state, and is the interface for other clients to use. It delegates all
state-specific method calls to the current
State
object.
State -
Defines all the methods that depend on the state of the object.
ConcreteState -
Implements the
State
interface, and implements specific behavior for one state.
The
Context
or the
ConcreteState
can determine the transition between states. This is not specified by the State
pattern. When the number of states is fixed, the most appropriate place to put the transition logic is in the
Context
.
However, you gain more flexibility by placing the transition logic in the
State
subclasses. In that case, each
State
determines the transition—which is the next State, under what circumstances the transition occurs, and
when it occurs. This makes it much easier to change part of the
State
transitions and add new
States
to the
system. The drawback is that each class that implements
State
is dependent on other classes—each
State
implementation must know at least one other
State
. If the
State
implementations determine the transition, the
Context
must provide a way for the
State
to set the new current
State
in the
Context
.
You can create state objects two using two methods: lazy instantiation or upfront creation.
Lazy instantiation creates the State objects at the time they are needed. This is useful only if the state rarely
changes. It is required if the different states are unknown at the start of the application. Lazy instantiation
prevents large, costly states from being created if they will never be used.
Up-front creation is the most common choice. All the state objects are created at startup. You reuse a state object
instead of destroying and creating one each time, meaning that instantiation costs are paid only once. This makes
sense if the state transitions are frequent—if a state is likely to be needed again soon.