State
behavioral
Allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
Intent
The State pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
Motivation
When an object's behavior depends on its state and it must change its behavior at runtime depending on that state, the State pattern is useful. It's an alternative to large conditional statements.
Structure
The pattern involves a State interface that declares state-specific behavior. ConcreteState classes implement behavior associated with a state of the Context. A Context maintains an instance of a ConcreteState that defines the current state.
Participants
- •Context - defines the interface of interest to clients and maintains an instance of a ConcreteState
- •State - defines an interface for encapsulating the behavior associated with a particular state
- •ConcreteState - each subclass implements a behavior associated with a state of Context
Pros
- ✓Localizes state-specific behavior
- ✓Makes state transitions explicit
- ✓State objects can be shared
- ✓Eliminates large conditional statements
Cons
- ✗Increases the number of classes
- ✗Can be overkill for simple state machines
Use Cases
TCP connection states
Document approval workflows
Vending machines
Game character states
Order processing
Implementation Tips
Considerations
- •Decide who defines state transitions
- •Consider creating and destroying State objects
- •Think about state sharing
- •Plan the state transition table
Tips
- •Keep states focused on specific behavior
- •Consider using a state factory
- •Document state transitions clearly
- •Use enums or constants for state identification