Behavioral PatternsState PatternMedium⏱️ ~3 min

State Pattern Structure and Participants

Core Components

The State Pattern involves three main participants that work together to enable dynamic behavior changes.

«interface»
State
+ handle(context): void
ConcreteStateA
+ handle(context): void
ConcreteStateB
+ handle(context): void
Context
- currentState: State
+ setState(state): void
+ 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

1. Client calls context.request()
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
Interview Tip: A key distinction is who controls state transitions. In State Pattern, the states themselves typically trigger transitions. If the Context controls all transitions, you might actually need a Finite State Machine (FSM) instead.
💡 Key Takeaways
State interface defines contract for all concrete states
Concrete states implement state-specific behavior and can trigger transitions
Context maintains reference to current state and delegates requests
Relationship between Context and State is composition (◆)
States know about Context to trigger transitions via setState()
📌 Examples
1Context delegates all operations to current state
2State A might transition to State B based on business logic
3Each state class is responsible for one state's behavior
← Back to State Pattern Overview