State Pattern
You'll learn how to let an object cleanly change its behavior when its internal state changes, making it appear as if the object changed its class.
The Core Idea
Imagine a vending machine: when it's idle, pressing buttons does nothing. Insert money, and suddenly the same buttons dispense products. The machine's behavior changes based on its state—but the machine itself is still the same object.
The State Pattern encapsulates state-specific behavior into separate state objects. Instead of littering your code with if-else or switch statements checking the current state, you delegate behavior to a state object. When the state changes, you swap out the state object, and the behavior changes automatically.
Why Use It?
Without the State Pattern, you'd have methods like:
if (state == IDLE) { /* do nothing */ }
else if (state == HAS_MONEY) { /* dispense */ }
else if (state == OUT_OF_STOCK) { /* show error */ }
This gets messy fast. With State Pattern, each state becomes its own class with its own behavior. The context object holds a reference to the current state and delegates requests to it.
The Structure
- Context: The object whose behavior changes (e.g., VendingMachine)
- State: An interface defining state-specific behavior
- Concrete States: Classes implementing different behaviors (IdleState, HasMoneyState, OutOfStockState)
When an event occurs, the current state handles it—and can even transition the context to a different state.
Comparison to Strategy Pattern
Both patterns use composition and delegation, but Strategy lets clients choose behavior, while State manages its own transitions internally based on context changes.
Key Takeaway: The State Pattern eliminates complex conditional logic by representing each state as an object, making state transitions explicit and behavior changes automatic.