# Purpose
The State pattern allows an object to alter its behavior when its internal state changes. It encapsulates variable states as independent objects.
# Problem
-
Variable Behavior: The object must act differently depending on its state at runtime.
-
Complex Conditionals: Avoid massive
if/switchstatements that depend on state variables.
# Solution
Create separate classes for each state. The main object (Context) delegates execution to the current state object.
# Structure
# Participants
- Context: Maintains the reference to the current state and delegates tasks.
- State (Interface): Defines the interface for the states.
- ConcreteState: Specific implementation of each behavior.
# When to Use It
When an object has clearly identifiable states that drastically alter its behavior in response to the same method calls.
# Advantages
-
verified
Single Responsibility: Logic for each state is isolated.
-
verified
Open/Closed: Easy to add new states without touching the context.
# Disadvantages
-
warning
Class Explosion: Many states mean many files.
-
warning
Overkill: Unnecessary for objects with few simple states.
# Example: Traffic Light
Management of Red, Yellow and Green states with automatic transition rules.
# Java Code
interface State { void handle(Context c); }
class GreenState implements State {
public void handle(Context c) {
System.out.println("Green light");
c.setState(new YellowState());
}
}
class Context {
private State state = new GreenState();
public void change() { state.handle(this); }
}
# Mapping Participants
- TrafficLightState: State Interface.
- RedState/GreenState: ConcreteStates.
- TrafficLightContext: Context.
# Conclusions
It eliminates the need for tangled conditionals and makes the transition flow explicit and easy to audit.
# Related Patterns
Strategy
Both use delegation, but State changes according to the internal state.