design patterns
State
The State pattern allows an object to alter its behavior when its internal state changes, appearing as though the object changed its class. It encapsulates state-specific behavior into separate state classes and delegates behavior to the current state object. The key participants are the Context (maintains an instance of a ConcreteState subclass that defines the current state), State (defines an interface for encapsulating the behavior associated with a particular state), and ConcreteState (each subclass implements behavior associated with a state of the Context). Think of a vending machine: its behavior (accept coin, dispense, etc.) changes entirely depending on its current state (idle, has money, dispensing, out of stock). Use State when an object's behavior depends on its state and it must change behavior at runtime, or when operations have large conditional statements that depend on the object's state.
Use Cases
- •Vending machines or ATM state management
- •Media player states (playing, paused, stopped)
- •Order lifecycle (pending, shipped, delivered, returned)
- •TCP connection states (listening, established, closed)