State
Replace state-based if/switch spaghetti with separate State classes β the object delegates its behavior to whichever State is currently active.
Intent & Description
π― Intent
Eliminate giant conditionals by encapsulating state-specific behavior into dedicated State objects.
π Context
Your object behaves differently depending on internal state β a vending machine that’s idle vs. dispensing vs. out of stock, a traffic light cycling through phases, a game character with different ability sets. The code is a wall of if-else or switch statements that grows every time a new state is added.
π‘ Solution
Define a State interface with methods for all state-specific behaviors. Create a concrete class for each state. The Context object holds a reference to the current State and delegates method calls to it. State transitions happen by swapping the reference.
Real-world Use Case
Source
π TL;DR
Each state = its own class. Context delegates to whichever state is active. Goodbye switch statements. Overkill for simple booleans, essential when states multiply.
Advantages
- Each state’s logic lives in its own class β no more 500-line switch statements.
- Add new states without touching existing state classes.
Disadvantages
- Complete overkill for simple two-state or rarely-changing state machines.
class State {
handle(context) {}
}
class ConcreteStateA extends State {
handle(context) {
console.log("State A handling context. Transitioning to B.");
context.transitionTo(new ConcreteStateB());
}
}
class ConcreteStateB extends State {
handle(context) {
console.log("State B handling context. Transitioning to A.");
context.transitionTo(new ConcreteStateA());
}
}