State Pattern Structure and Participants
Core Components
The State Pattern involves three main participants that work together to enable dynamic behavior changes.
+ request(): void
Participant Responsibilities
1. State Interface
Defines the interface for encapsulating behavior associated with a particular state of the Context. All concrete states must implement this interface to ensure the Context can work with any state interchangeably.
2. Concrete State Classes
Each implements the State interface and provides state-specific behavior. These classes contain the logic for what should happen when the Context is in this particular state. Crucially, concrete states can trigger state transitions by calling context.setState(newState).
3. Context
Maintains a reference to a concrete state object that represents its current state. The Context delegates state-specific requests to the current state object. It provides a setState() method allowing states to change the context's current state.
Interaction Flow
2. Context delegates to currentState.handle(context)
3. State executes behavior
4. State may call context.setState(newState)
5. Future requests now go to the new state