State Pattern

The State pattern is used when the behavior of an Object changes based on its internal state.

A simplistic way of doing this would be to have the state stored in private property, and run a chain of if-else blocks on this state, to define the behavior. Such an approach may be good when the state based variation is minimal. But, it can soon go out of control as the size of your application increases.

The State Pattern provides an elegant solution. It provide a systematic and lose-coupled way to achieve this through Context and State implementations.

Essentially, it is based upon an object instance of each state - that defines the behavior. Thus, the behavior is assigned to the owner - along with the state.

  • Context: Defines an interface to client to interact. It maintains references to concrete state object which may be used to define current state of object.
  • State: Defines interface for declaring what each concrete state should do.
  • ConcreteState: Provides implementation for methods defined in State.

In the State design pattern, an object's behavior is changed at runtime - depending on the state. This removes the dependency on the if/else or switch/case conditional logic. The State design pattern also improves Cohesion since state-specific behaviors are aggregated into the ConcreteState classes, which are placed in one location in the code.

However, if it is not used judiciously, the state pattern can bump up the number of classes in your application - making it difficult to maintain.