Allow an object to alter its behavior when it’s internal state changes. The object will appear to change its class.
State pattern is one of the behavioral design patterns which is used when an Object changes its behavior based on its internal state.
If we need to change the behavior of an object based on its state, we can define state variable in the Object and use if-else condition block to perform different actions based on the state. This approach is inflexible as we need to add an if-else block in the class for the new state. However, State pattern is used to provide a systematic and loosely-coupled way to achieve this (state change) through Context and State implementations.
The classes and objects participating in state design pattern:
It defines the interface of interest to clients and maintains an instance of a ConcreteState subclass that defines the current state.
It defines an interface for encapsulating the behavior associated with a particular state of the Context.
Each subclass implements a behavior associated with a state of Context.
What problems can the State design pattern solve?
1. An object should change its behavior when it’s internal state changes.
2. State-specific behavior should be defined independently. That is, new states should be added and the behavior of existing states should be changed independently.
Implementing state-specific behavior directly (using if-else block) within a class is inflexible because it commits the class to a particular behavior and makes it impossible to add a new state or change the behavior of an existing state later without changing the class (developers need to add a new if-else block for new state).
What solution does the State design pattern describe?
1. Define separate (state) objects that encapsulate state-specific behavior for each state. That is, define an interface (State) for performing the state-specific behavior, and define classes that implement the interface for each state.
2. A class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly.
This makes a class independent of how state-specific behavior is implemented. New states can be added by defining new state classes. A class can change its behavior at run-time by changing its current state object.