What is the State Pattern?
Updated Apr 28, 2026
Short answer
A behavioral pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class.
Deep explanation
The State pattern extracts state-related behaviors into separate state classes. The context object delegates the execution to the current state object. It cleanly replaces massive finite-state machine switch statements.
Real-world example
A media player's 'Play' button behaving differently depending on whether the player is currently playing, paused, or stopped.
Common mistakes
- Applying State pattern for simple conditions where a basic boolean flag would suffice.
Follow-up questions
- Who defines the state transitions?