State
Category
Behavioral pattern
Problem
Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Useful for objects with complex state-dependent behavior that would otherwise require large conditional statements.
Solution
- Define a State interface that encapsulates behavior specific to each state
- Create ConcreteState classes, each implementing behavior for a specific state
- The Context holds a reference to the current State and delegates behavior to it
- State transitions are handled by the Context or by the States themselves
Structure
- Context: Defines the interface of interest to clients; maintains a State instance
- State: Interface for encapsulating behavior associated with a particular state
- ConcreteState: Implements behavior for a specific state
Key Benefits
- Encapsulates state-specific behavior — Each state’s logic is in its own class
- Eliminates large conditionals — No giant switch/if-else chains for state logic
- Open/Closed Principle — New states can be added without modifying existing code
Trade-offs
- More classes — Each state becomes a separate class
- State transition complexity — Transitions between states can be hard to manage
When to Use
- An object’s behavior depends on its state, and it must change behavior at runtime depending on the state
- Operations have large, multipart conditional statements that depend on the object’s state
- State-specific behavior should be isolated from other behavior