Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps
Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps
Quick reference for behavioral patterns. The table below is a map, not a substitute for deep pages — especially for Observer lifecycle and Command undo.
| Pattern Name | Distinctive Feature | Applicability | An Example | Pros | Cons |
|---|---|---|---|---|---|
| Iterator | Provides a way to access elements of a collection sequentially without exposing its underlying representation | When you need to provide a standard way to traverse through a collection without exposing its implementation | Browsing through a playlist | Simplifies client code and hides complexity of the collection | Iterator state management can be complex |
| Strategy | Enables an algorithm's behavior to be selected at runtime | When there are multiple ways to achieve a task and you want to determine the algorithm at runtime | Different compression algorithms | Flexibility to switch algorithms; isolation of algorithm implementation | Complexity due to additional classes; clients must be aware of different strategies |
| Template Method | Defines the skeleton of an algorithm in an operation, deferring some steps to subclasses | When the core structure of an algorithm should not change, yet some steps are open to being overridden | Frameworks defining application structure | Promotes code reuse and enforces a predefined algorithm structure | Can lead to less flexibility in subclasses; harder to maintain |
| Observer | Notifies multiple objects about state changes | When changes in one object's state require other objects to be notified | Real-time data feeds | Loose coupling between subject and observers | Risk of unintended performance issues |
| Command | Encapsulates a request as an object | For operations that need to be executed, undone, or logged | User actions in GUI applications | Decouples command execution from usage | Can lead to numerous concrete command classes |
| State | Allows objects to alter their behavior when their internal state changes | For objects whose behavior depends on their state and can change at runtime | Different modes in a game | Localizes state-specific behaviors | Increases the number of classes |
| Chain of Responsibility | Delegates commands to a chain of processing objects | For scenarios where multiple objects can handle a request, but the handler is unknown | Help systems in applications | Decouples request sender and receiver | Handling can become inefficient |
| Mediator | Centralizes complex communications between related objects | To reduce direct communications between multiple objects | Chat application | Simplifies interactions between groups of objects | Mediator can become overly complex |
| Memento | Captures and externalizes an object's internal state | For undo functionality or state save-and-restore | Undo feature in editors | Preserves encapsulation boundaries | Can be memory-intensive |
| Visitor | Separates an algorithm from the objects on which it operates | When operations need to be performed on a group of similar kinds of objects | Processing different types of document elements in a word processor | Simplifies adding new operations; centralizes related operations | Can lead to a bloated visitor interface; harder to maintain when the object structure changes |
Pattern taxonomy recap
| Family | What it solves | Canonical patterns |
|---|---|---|
| Creational | How objects are instantiated and who decides the concrete type | Singleton, Factory Method, Abstract Factory, Builder, Prototype |
| Structural | How classes/objects are composed into larger structures | Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy |
| Behavioral | How objects communicate and how responsibilities are distributed | Observer, Strategy, Command, State, Template Method, Iterator, Mediator, Memento, Chain of Responsibility, Visitor |
Behavioral patterns: when to use
| Pattern | Use when | Skip when |
|---|---|---|
| Observer | One object must notify many dependents; subscribe/unsubscribe is explicit | Forgotten unsubscribe leaks; notify while mutating the list (CME); process-boundary needs an event bus, not in-process Observer |
| Strategy | Multiple interchangeable algorithms | A single algorithm or a simple lambda is enough |
| Command | Requests must be queued, logged, undone, or replayed (store inverse or memento) | The request is simple and synchronous with no undo/history need |
| State | Behavior changes dramatically based on internal state | Only one or two states exist; an enum is cleaner |
| Template Method | An algorithm skeleton is fixed but steps vary | Every step varies or the superclass becomes fragile |
| Iterator | Hide traversal details of a collection | The language already provides adequate iteration |
| Mediator | Many objects communicate through a central coordinator | The mediator becomes a bottleneck or hidden global state |
| Chain of Responsibility | More than one handler may process a request | Order is ambiguous or every request needs every handler |
| Visitor | Add operations to a stable class hierarchy without modifying it | The hierarchy changes often; double dispatch is hard to follow |
Observer: senior failure modes (must know)
- Forgotten unsubscribe leaks. A long-lived subject (singleton event bus, app shell) retains every observer that never unregistered. UI components and request-scoped services must unsubscribe on dispose/teardown.
- Notify while mutating the list. An observer that unsubscribes (or subscribes another) during
publishcan throwConcurrentModificationExceptionor skip listeners. Snapshot the list before notify, or use a concurrent structure and document re-entrancy rules. - Prefer an event bus / message broker at process boundaries. In-process Observer is for same-JVM collaborators. Cross-service notification needs durable messaging, consumer groups, and at-least-once handling — not a list of callbacks.
Command and undo
Command's value is deferred execution, logging, queuing, and undo. A command that cannot invert itself either stores enough state for reverse application or pairs with a Memento of the receiver. "Encapsulate a method call" alone is not enough to justify the pattern.
Interview trap box
- "Observer and Strategy look the same." Observer notifies many subscribers about a state change; Strategy swaps one algorithm in a context.
- "Command is just a wrapper." The value is in deferred execution, undo, and queuing — not the wrapping itself.
- "State pattern is only for state machines." It models state-specific behavior as classes, which is a design choice, not the only way to build a state machine.
- "Visitor solves the expression problem." Only for stable hierarchies; adding a new type requires changing every visitor.
- "Observer is fine forever." Without unsubscribe discipline and CME-safe notify, it becomes a leak and flaky crash source under load.
- "Strategy and Template Method are the same." Strategy composes interchangeable algorithms (runtime-swappable, testable in isolation); Template Method inherits a fixed skeleton with overridable hooks (compile-time, single fragile base class). Prefer Strategy when you want isolation and a runtime swap.
🤖 Don't fully get this? Learn it with Claude
Stuck on Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Build the mental picture, not memorization.
I just read a lesson on **Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps** (OO & Low-Level Design) and want to truly understand it. Explain Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Socratic — adapts to where you're stuck.
Teach me **Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Active recall exposes what you missed.
Quiz me on **Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Intuition + hook + flashcards for long-term memory.
Help me remember **Behavioral Patterns — Quick Reference, When-to-Use & Interview Traps** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.