Design Pattern means that “we had some problem then we found the solution and gave name to this solution” and State design is also one of the solution so we need to find the problem that State has solved and how ?
This design pattern comes under Behavioral Category (It tells that how objects are communicating with each other (objects have been created already)).
C++ State Design Pattern :
It defines that allow an object to alter(change) its behaviour when its internal state changes, the object will appear to change its class.
In layman language:
Object Oriented State machine.
State machine scenarios, How to handle state machine with object oriented principle (with the help of classes).
Create one class named as context, it will have pointer of another class named as state (this is hierarchy) and each derived class will represent specific state. context object will behave same like state machine, this solution called as “state design pattern“.
When we will use state design pattern:
- When we have many states that needs to be handled.
- when we want to handle each state in separate class.
- Loose coupling (each state is represented in separate class so we can handle the different sate in different class).
- Flexible (We can add new state at any time without polluting existing code).
- There is state class and its derive class represent each state.
- There is context class having state class pointer.
- Transition of state can be handled at two places : in context class or each derive class.
- State class mostly created as singleton class.
- This pattern structure similar to bridge pattern but in bridge there is separate hierarchy.
Class Diagram of real example:
Real Class Diagram Example:
Source code with real example: