The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class. The State pattern switches between internal classes in such a way that the enclosing object appears to change its class.
Many objects are required to have a dynamically changing set of attributes called their state. Such objects are called stateful objects. An object’s state will usually be one of a predetermined set of values. When a stateful object becomes aware of an external event, its state may change. The behavior of a stateful object is determined by its state.
Context
– defines the interface of interest to clients
– maintains an instance of a ConcreteState subclass that defines the current state
State
– defines an interface for encapsulating the behavior associated with a particular state of the Context.
ConcreteState subclasses
– each subclass implements a behavior associated with a state of the Context
- The State pattern localizes state-specific behavior in an individual class for each state, and puts all the behavior for that state in a single object.
- It eliminates the necessity for a set of long, look-alike conditional statements scattered through the program’s code.
- It makes transition explicit. Rather than having a constant that specifies which state the program is in, and that may not always be checked correctly, this makes the change explicit by copying one of the states to the state variable.
- This approach generates a number of small class objects, but in the process, simplifies and clarifies the program.
- In Java, all of the States must inherit from a common base class, and they must all have common methods, although some of those methods can be empty.
- State behavior is localized and partitioned using objects, which simplifies adding or modifying state behavior and transitions.
- State objects might be reuseable for other systems, particularly if the state objects contain no data.
The code example implements an Appointment Calendar system. The abstract class State implements two methods: Edit and Save. The two concrete state classes are Clean State and Dirty State. The Appointment Calendar system is in the Clean State when no changes have been made to it since the last Save. The Appointment Calendar system is in the Dirty State when there have been changes since the last Save. Depending on the current state and the input from the user (Edit or Save), the next state is set to Clean or Dirty.
Strategy: Encapsulate related algorithms in classes that implement a common interface. Allows to switch algorithms.
Polymorphism: Same interface, different implementation
Flyweight: If instances of a class contain the same information, multiple instances are avoided by sharing one instance.
Modified:
6-Apr-2004
Sowmya Narayanan