State
Allows an object to alter its behavior when its internal state changes, appearing as if the object has changed its class.
errorWhat Problem Does the State Pattern Solve?
Objects that behave differently depending on their current state often accumulate large conditional blocks that check state flags on every method call. As new states are added, these conditionals grow, scatter related logic across the class, and make transitions hard to reason about.
check_circleHow the State Pattern Works
Represent each state as a separate class implementing a common State interface. The Context holds a reference to the current state object and delegates behavior to it. State transitions happen by replacing the current state object, concentrating each state's logic in one place and making new states trivially addable.
State Pattern Architecture
Rendering diagram...
Implementation by Language
State Pattern in the Real World
“Think of a traffic light. The light itself (context) doesn't change its wiring, but its active state—red, yellow, or green—completely determines what drivers should do. Each color has its own rules, and the light transitions through states on a timer. Adding a flashing-yellow state only requires defining that state's rules, not rewiring the entire light.”
Frequently Asked Questions
helpHow does the State pattern eliminate complex if/else chains?
Instead of checking the current state in every method (if state === 'playing' then ...), each state is a separate class with its own implementation of every method. The context delegates to the current state object. Adding a new state means adding a new class, not modifying existing conditionals.
helpWho should be responsible for state transitions?
Either the State objects themselves (each state knows its successors) or the Context (centralized transitions). State-driven transitions are more encapsulated but can create tight coupling between state classes. Context-driven transitions are easier to trace but centralize logic.