Behavioral patterns: algorithms and collaboration
Behavioral patterns encapsulate what objects do and how they communicate. These five cover ~80% of LLD interview designs.
| Pattern | Core idea | Canonical LLD use |
|---|---|---|
| Strategy | Swap algorithm at runtime | Pricing rules, eviction policies, spot allocation |
| Observer | One-to-many notification | Inventory low-stock alerts, order status updates |
| Command | Encapsulate request as object | Undo/redo, job queue, macro transactions |
| State | Object behavior changes with internal state | Vending machine, TCP connection, order lifecycle |
| Template Method | Skeleton algorithm, subclass fills steps | AbstractClass.process() with hook() overrides |
Strategy vs State
Both use polymorphism, but Strategy is chosen externally (client injects PricingStrategy), while State transitions internally (vendingMachine.setState(new DispensingState())). If the interviewer describes "modes that change behavior," ask whether transitions are driven by the object or the caller.
Observer vs pub/sub
Classic Observer couples subjects to concrete observer lists. Event buses decouple further but add indirection. In LLD, Order notifying InventoryService and EmailService via an OrderListener interface is enough — don't build Kafka on the whiteboard unless asked.
Chain of Responsibility (brief)
Handler chain for requests (auth → validation → processing). Each link forwards or handles. Appears in middleware pipelines and exception handling — mention if interviewer describes "multiple checks before action."
Senior-level signal
Map pattern to requirement explicitly: "You said pricing varies by membership tier — that's Strategy. Checkout holds a PricingStrategy; new tiers are new classes, not new if branches." For Command, mention the invoker (RemoteControl, JobQueue) that doesn't know what the command does — that's the decoupling win.
Where this goes next
Pattern Selection & Anti-Patterns teaches when to stop adding patterns and how to recover from over-engineered whiteboard designs.
Further Reading
Practice Tasks (Optional)
Design or implement locally in any language — no autograding. Focus on class structure, extensibility, and being able to explain trade-offs out loud.
- Strategy for pricing rules30m
Design a Checkout class that accepts a PricingStrategy interface (Regular, PremiumMember, SeasonalSale). Show how to add a new strategy without editing Checkout. Implement in your preferred language if time allows.