State Design Pattern — a behavioral design pattern that allows an object to change its behavior when its internal state changes.
State Design Pattern
- The State Design Pattern is a Behavioral Design Pattern and one of the Gang of Four design patterns.
- The State allows an object to alter its behavior when its internal state changes.
- The State pattern is similar to the concept of finite-state machines.
- The State pattern is also similar to the Strategy Design Pattern which provides a way to switch a strategy through invocations of methods defined in the pattern’s interface.
- The State pattern encapsulates varying behavior for the object based on its internal state change.
- The State pattern provides a cleaner way for an object to change its behavior at runtime.
- By using the State pattern, the object changes its behavior when its internal state changes.
- If we implement State-Specific behavior directly in the class, then we will not be able to change it without modifying the class.
- In-State pattern, State-specific behavior should be defined independently because adding new states should not affect the behavior of existing states.
- The context class delegates state-specific behavior to its current state object instead of implementing state-specific behavior directly.
- This allows us to make our context class independent of how state-specific behavior is implemented. New state classes can be added without modifying context class.
- The context class can change its behavior at run-time by changing its current state object.
- To implement the State Design Pattern, we create a State interface to define some action. And then concrete classes that represent various states and a context object whose behavior varies as its state object changes.
- The mixer in the kitchen is a good example of a state pattern, which has a motor and a control interface. Using the knob we can increase/decrease the speed of the mixer. Based on the speed state the behavior changes.
- The TV which can be operated with a remote controller is another example of a State pattern. We can change the state of the TV by pressing buttons on the remote. But the state of TV will change or not, it depends on the current state of the TV. If the TV is switched OFF then only possible next state can be switch ON. And if TV is ON, we can switch it OFF, mute, or change aspects and source. But if TV is OFF, nothing will happen when we press the remote buttons.
- Java Threads are another good example of State pattern since they have defined states as New, Runnable, Blocked, Waiting, Timed Waiting and Terminated.