State pattern
The state pattern is a behavioral software design pattern that allows an object to alter its behavior when its internal state changes. This pattern is close to the concept of finite-state machines. The state pattern can be interpreted as a strategy pattern, which is able to switch a strategy through invocations of methods defined in the pattern's interface.
The state pattern is used in computer programming to encapsulate varying behavior for the same object, based on its internal state. This can be a cleaner way for an object to change its behavior at runtime without resorting to conditional statements and thus improve maintainability.
Overview
The state design pattern is one of twenty-three design patterns documented by the Gang of Four that describe how to solve recurring design problems. Such problems cover the design of flexible and reusable object-oriented software, such as objects that are easy to implement, change, test, and reuse.The state pattern is set to solve two main problems:
- An object should change its behavior when its internal state changes.
- State-specific behavior should be defined independently. That is, adding new states should not affect the behavior of existing states.
- Define separate objects that encapsulate state-specific behavior for each state. That is, define an interface for performing state-specific behavior, and define classes that implement the interface for each state.
- A class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly.
Structure
In the accompanying Unified Modeling Language class diagram, theContext class doesn't implement state-specific behavior directly. Instead, Context refers to the State interface for performing state-specific behavior, which makes Context independent of how state-specific behavior is implemented. The ConcreteStateA and ConcreteStateB classes implement the State interface, that is, implement the state-specific behavior for each state. The UML sequence diagram shows the run-time interactions:The
Context object delegates state-specific behavior to different State objects. First, Context calls handle on its current state object, which performs the operation and calls setState on Context to change context's current state to ConcreteStateB. The next time, Context again calls handle on its current state object, which performs the operation and changes context's current state to ConcreteStateA.Example
This is a C++ example demonstrating the state pattern.- include
- include
class Fan;
class OffState;
class LowSpeedState;
class HighSpeedState;
// Abstract State
class FanState ;
// Context
class Fan ;
// Concrete States
class OffState : public FanState ;
class LowSpeedState : public FanState ;
class HighSpeedState : public FanState ;
int main