🎨 Design Patterns (Gang of Four)
Beginner
What is the State design pattern?
Answer
The State pattern allows an object to alter its behavior when its internal state changes, making it appear to change its class. Instead of large conditional (if/switch) blocks based on a state variable, the context object delegates behavior to a state object that represents the current state. When the state changes, the context swaps its state object. A vending machine is a perfect example — it behaves very differently when NoMoneyState vs HasMoneyState vs OutOfStockState. This makes adding new states easy without modifying existing state classes, following the Open/Closed Principle.