State
Intent
Lets an object alter its behaviour when its internal state changes, as if it changed its class.
Problem
A document's publish() behaves differently in draft, moderation and published states; conditionals spread everywhere.
Solution
Move state-specific behaviour into state classes; the context delegates to the current state.
Real-world analogy
A phone's buttons do different things when it is locked, unlocked or low on battery.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Context — Context stores a reference to the current state and delegates state-specific work to it.
- 2State — State declares the state-specific methods.
- 3ConcreteStates — Concrete States implement behaviour for one state and may trigger transitions.
- 4Context — Both the context and the states can switch the current state.
Code example
Applicability
Use State when behaviour depends on many states that change often.
Use State when massive conditionals on state fields.
Pros and cons
Pros
- Single Responsibility per state
- Removes bulky conditionals
Cons
- Overkill for a few simple states
Check yourself
A vending machine behaves differently when idle, waiting for payment, dispensing or out of stock.
Saved in this browser only. Part of Behavioral patterns (0/11).