State - Harsh4999/Design-Patterns GitHub Wiki
State
USE
- State design pattern allows our objects to behave differently based on its internal state.
- This pattern allows to define the state specific behaviors in seperate classes.
- State transition can be triggered by themselves in which case each state knows about at least one other state's existence.
- We can add new states witthout changing main class
UML
- Context: Class whose state is now an object. Client code works with this class delegates operation to current state.Context holds a state object which defines the actual behavior of the class
- State: Interface which defines operations
- Concrete State: Implementation of an unique behavior of object tied to this state. They represent specific values which our state can take.
Implementation
- Identify values which will be a state for an object. Each state value becomes a specific class.
- We have to decide how our state transition will happen from one state to other.
- Client will be unaware of states.
- Ask a client to initialize the state after that states should transit by themselves.
- Using flyweight pattern we can share states which do not have any instance variables.
- Eg: Java Server Face pattern.
- Implementing this may lead to lot of classes. It may be complicated if states are high in number