Behavioral Patterns
Use Strategy, Observer, State, Command, Chain of Responsibility and Template Method to organise changing behaviour, the patterns most used in LLD rounds.
Intermediate · about 8 hours · difficulty 3/5
Learn first: Creational and Structural Patterns
Behavioral patterns are about who does what and how objects communicate. They show up constantly in low-level design: pricing rules, event notifications, state machines and undo systems.
The ones to know well
- Strategy: swap an algorithm at runtime behind an interface. Parking fee calculation, sorting policies, payment methods and pricing all fit. This is the single most useful LLD pattern because it directly implements Open/Closed.
- Observer: subjects notify subscribers when something changes. Stock price alerts, YouTube subscriptions, UI events. Know the risk of memory leaks when observers never unsubscribe.
- State: an object changes behaviour when its internal state changes. A vending machine (Idle, HasMoney, Dispensing) or an order lifecycle is cleaner as State classes than as nested
ifchecks on an enum. - Command: wrap a request as an object so you can queue, log or undo it. Text editor undo/redo and job queues.
- Chain of Responsibility: pass a request along handlers until one handles it. Logging levels, approval workflows, middleware, ATM cash dispensing (2000, 500, 100 notes).
- Template Method: a base class fixes the algorithm skeleton; subclasses fill in steps.
- Iterator (optional): traverse a collection without exposing its internals.
Choosing between them
- Behaviour picked by the caller or config: Strategy.
- Behaviour driven by the object's own state: State.
- Many parties need to react to an event: Observer.
- Actions must be stored or undone: Command.
Good enough to move on: given a design prompt like "vending machine" or "notification service", you can name the pattern that fits, justify it in one sentence and sketch the classes.
Key concepts
- Strategy
- Observer
- State
- Command and undo
- Chain of Responsibility
- Template Method
- Iterator
- Mediator
Mini project
Implement a vending machine using the State pattern, pluggable pricing with Strategy, low-stock alerts with Observer, and an admin action log with Command that supports undoing the last restock.
Check yourself
When would you choose the State pattern over Strategy, given that both replace conditionals with polymorphic classes?
Free resources
- Refactoring Guru: Behavioral patterns (Refactoring Guru)
- SourceMaking: Behavioral patterns (SourceMaking)