State Pattern: Definition, Example, and When to Use
State Pattern is a design pattern that allows an object to change its behavior when its internal state changes, making it appear as if the object changed its class. It helps manage state-specific behavior by encapsulating states into separate classes and delegating state-related actions to them.How It Works
Imagine a vending machine that behaves differently depending on whether it has money inserted or not. Instead of writing many if-else checks everywhere, the State Pattern lets the machine switch between different state objects like NoMoneyState and HasMoneyState. Each state object knows how to handle actions like inserting money or dispensing a product.
This pattern works by having a context object hold a reference to a state object. When the context's state changes, it simply switches the state object it uses. This way, the context's behavior changes without changing its own code, making the design cleaner and easier to maintain.
Example
from abc import ABC, abstractmethod class State(ABC): @abstractmethod def press_switch(self, switch): pass class OnState(State): def press_switch(self, switch): print("Turning light OFF") switch.state = OffState() class OffState(State): def press_switch(self, switch): print("Turning light ON") switch.state = OnState() class LightSwitch: def __init__(self): self.state = OffState() def press(self): self.state.press_switch(self) # Usage light = LightSwitch() light.press() # Turning light ON light.press() # Turning light OFF light.press() # Turning light ON
When to Use
Use the State Pattern when an object must change its behavior at runtime depending on its internal state, and when you want to avoid large conditional statements scattered across your code. It is especially useful when state-specific behavior is complex or when new states might be added later.
Real-world examples include:
- Media players switching between playing, paused, and stopped states.
- Network connections changing between connected, disconnected, and reconnecting states.
- Document editors handling different modes like read-only, edit, or review.
Key Points
- The State Pattern encapsulates state-specific behavior into separate classes.
- It allows an object to change behavior by changing its current state object.
- It reduces complex conditional logic and improves code maintainability.
- It supports adding new states without modifying existing code.