What is the State Pattern?
- It allows an object to alter its behavior when the internal state changes
- The object will appear to change its class
How Does It Work?
- A State interface is created that has all the actions the main class needs.
- A concrete class is created for each state the system can be in (implementing the State)
- Each state knows when a state change happens and sets the container's state class to the new state (object)
- The container always calls state.method()
- The states have to have a reference to the container since they changed its State
State Vs Strategy
- User of context in state isn't aware of state objects
- User of Strategy specifies objects to change the algorithm
- Strategy is a more flexible alternative to subclassing (changing the composition changes the behavior)
- State is an alternative to using conditionals
Context Transitions Vs State Transitions
You can decouple the states from the Context by having the Context choose the next state
- If Transitions are fixed, put in Context
- If Transitions are dynamic, put in state (state knows the Transition to the next state)
Do States Maintain State?
- No, they choose Transitions
- This means contexts can share the same strategies