Loading content...
Behavioral design patterns—all eleven of them in the classical Gang of Four catalog—address object interaction and responsibility distribution. Yet the sheer number of patterns creates a paradox: knowing the patterns is far easier than knowing when to apply each one.
Consider this common scenario: you're designing a system where objects need to respond to state changes. Should you use Observer for publisher-subscriber semantics? Mediator to centralize communication? Chain of Responsibility for sequential handling? Or perhaps State if the changes relate to object behavior transitions?
The difference between a journeyman developer and a senior architect often lies not in pattern knowledge, but in pattern selection intuition—the ability to instantly recognize which pattern best fits a given problem space. This intuition isn't magic; it's built through systematic comparison and deliberate practice.
By the end of this page, you will understand the core purpose, participants, and distinguishing characteristics of every behavioral pattern. You'll develop a mental model for comparing patterns along multiple dimensions and recognize the subtle distinctions that determine optimal selection.
Before diving into detailed comparisons, let's establish the complete landscape of behavioral patterns. The Gang of Four defined eleven behavioral patterns, each addressing a specific aspect of how objects communicate and distribute responsibilities.
The Classification Framework:
Behavioral patterns can be organized along several dimensions:
| Pattern | Classification | Primary Purpose | Key Insight |
|---|---|---|---|
| Chain of Responsibility | Object | Pass requests along a chain of handlers | Decouple sender from receivers |
| Command | Object | Encapsulate requests as objects | Enable undo, queue, and log operations |
| Interpreter | Class | Define grammar representations | Implement domain-specific languages |
| Iterator | Object | Sequential access without exposing internals | Unify collection traversal |
| Mediator | Object | Centralize complex communications | Replace many-to-many with hub-and-spoke |
| Memento | Object | Capture and restore object state | Externalize state without breaking encapsulation |
| Null Object | Object | Provide default no-op behavior | Eliminate null checks throughout code |
| Observer | Object | Notify dependents of state changes | Enable loose-coupled event distribution |
| State | Object | Change behavior when state changes | Eliminate conditional state logic |
| Strategy | Object | Define interchangeable algorithms | Enable algorithm selection at runtime |
| Template Method | Class | Define algorithm skeleton with customizable steps | Invert control between framework and application |
| Visitor | Object | Add operations without modifying classes | Separate algorithms from object structures |
While not part of the original Gang of Four catalog, the Null Object pattern is widely recognized as an essential behavioral pattern. It addresses the ubiquitous problem of null reference handling and fits naturally within the behavioral pattern family.
Each behavioral pattern exists because the Gang of Four identified a recurring design problem that required a structured solution. Understanding the precise intent of each pattern is foundational to accurate selection.
The Intent Triangle:
Every pattern's intent can be decomposed into three components:
Memorizing Intent vs Understanding Intent:
Rote memorization of these intents is insufficient for pattern selection. True understanding requires recognizing the problem shape that each intent addresses:
Beyond intent, behavioral patterns can be compared by their structural characteristics—the participants involved and how they collaborate. This structural analysis reveals deeper similarities and differences.
| Pattern | Core Participants | Key Relationship | Communication Direction |
|---|---|---|---|
| Chain of Responsibility | Handler, ConcreteHandler, Client | Handlers form a linked chain | Unidirectional (along chain) |
| Command | Command, ConcreteCommand, Invoker, Receiver | Invoker holds Command; Command knows Receiver | Decoupled via Command object |
| Interpreter | AbstractExpression, TerminalExpression, NonterminalExpression, Context | Expressions form tree structure | Recursive evaluation |
| Iterator | Iterator, ConcreteIterator, Aggregate, ConcreteAggregate | Iterator traverses Aggregate | Sequential access |
| Mediator | Mediator, ConcreteMediator, Colleague | Colleagues communicate via Mediator only | Hub-and-spoke (star topology) |
| Memento | Originator, Memento, Caretaker | Caretaker holds Mementos; Originator creates/restores | State snapshot and restore |
| Null Object | AbstractObject, RealObject, NullObject | NullObject provides default behavior | Polymorphic substitution |
| Observer | Subject, ConcreteSubject, Observer, ConcreteObserver | Subject notifies Observers | One-to-many broadcast |
| State | Context, State, ConcreteState | Context delegates to current State | Behavior delegation |
| Strategy | Context, Strategy, ConcreteStrategy | Context delegates to Strategy | Algorithm delegation |
| Template Method | AbstractClass, ConcreteClass | Subclass overrides hook methods | Inheritance-based customization |
| Visitor | Visitor, ConcreteVisitor, Element, ConcreteElement, ObjectStructure | Elements accept Visitors; Visitors visit Elements | Double dispatch |
Notice how Strategy and State share nearly identical structures—both have a Context that delegates to an abstract interface with concrete implementations. The difference is semantic: Strategy changes algorithms while State changes object behavior based on internal state. Similarly, Command and Memento both encapsulate something as an object, but Command encapsulates requests while Memento encapsulates state.
Class-Based vs Object-Based Patterns:
Two behavioral patterns rely primarily on inheritance (class patterns):
The remaining nine patterns rely on object composition:
Certain behavioral patterns are frequently confused with each other due to superficial similarities. Mastering the distinctions between these commonly confused pairs is essential for accurate pattern selection.
Strategy vs State: The Structure Twins
These patterns have nearly identical class diagrams, making them the most frequently confused pair. The distinction lies entirely in intent and usage semantics.
Ask: 'Who decides when to switch?' If the client decides → Strategy. If the object itself decides based on its internal logic → State.
To facilitate systematic pattern comparison, we can evaluate all behavioral patterns across multiple dimensions. This matrix provides a quick reference for pattern selection based on specific requirements.
| Pattern | Sender-Receiver Coupling | Communication Type | Knowledge Required |
|---|---|---|---|
| Chain of Responsibility | Very Low (sender knows nothing) | Sequential request passing | Handler interface only |
| Command | Low (via command object) | Request encapsulation | Command interface only |
| Interpreter | Medium (expression tree) | Recursive interpretation | Grammar structure |
| Iterator | Low (via iterator) | Sequential access | Iterator interface only |
| Mediator | Low-Medium (via mediator) | Centralized coordination | Colleague and mediator interfaces |
| Memento | Low (via memento) | State capture/restore | Memento interface only |
| Null Object | None (transparent) | Polymorphic substitution | None (uses existing interface) |
| Observer | Low (subscription) | One-to-many broadcast | Observer interface only |
| State | Medium (context-state) | Behavior delegation | State interface and transitions |
| Strategy | Low (via strategy) | Algorithm delegation | Strategy interface only |
| Template Method | High (inheritance) | Inheritance-based hook calls | Base class structure |
| Visitor | Medium-High (double dispatch) | Operation application | Element hierarchy |
| Pattern | Runtime Flexibility | Extension Mechanism | Open/Closed Compliance |
|---|---|---|---|
| Chain of Responsibility | High (chain configurable) | Add new handlers | Excellent |
| Command | High (commands composable) | Add new commands | Excellent |
| Interpreter | Medium (grammar fixed) | Add new expressions | Good for expressions |
| Iterator | Medium (traversal fixed) | Add new iterators or aggregates | Good |
| Mediator | Medium (mediator central) | Modify mediator logic | Moderate (mediator concentration) |
| Memento | High (state snapshots) | Add new state types | Excellent |
| Null Object | High (drop-in replacement) | Use existing interface | Excellent |
| Observer | High (dynamic subscription) | Add new observers | Excellent |
| State | High (runtime transitions) | Add new states | Excellent |
| Strategy | High (runtime swappable) | Add new strategies | Excellent |
| Template Method | Low (inheritance bound) | Subclass and override | Moderate (requires subclassing) |
| Visitor | High for operations | Add new visitors | Excellent for operations; poor for elements |
Visitor exemplifies a classic Open/Closed tradeoff: it makes adding new operations trivial (open for extension) while making adding new element types difficult (requires modifying all visitors). This is the reverse of the typical class hierarchy tradeoff. Choose Visitor when operations change frequently but element types are stable.
Behavioral patterns don't exist in isolation. Understanding where patterns overlap—and where they don't—helps you make nuanced selection decisions.
The Overlap Spectrum:
Some patterns address similar problem spaces but from different angles:
Distinguishing by Primary Concern:
When patterns overlap, determine which primary concern dominates your requirements:
| Concern | Primary Pattern | Secondary Patterns |
|---|---|---|
| Decoupling sender from receiver | Chain of Responsibility | Command, Observer |
| Reifying actions as objects | Command | Strategy, Memento |
| Broadcasting state changes | Observer | Mediator |
| Centralizing control logic | Mediator | Observer |
| Capturing state without exposure | Memento | Command |
| Handling absence gracefully | Null Object | Strategy, State |
| Changing behavior by state | State | Strategy |
| Choosing algorithms dynamically | Strategy | State, Template Method |
| Defining extensible operations | Visitor | Iterator |
| Fixed algorithm with hooks | Template Method | Strategy |
| Uniform collection access | Iterator | Visitor |
We've covered the complete landscape of behavioral patterns, their intents, structures, and distinctions. Let's consolidate the key insights for pattern selection:
What's Next:
With a solid foundation in pattern comparison, the next page provides a systematic decision tree for selecting behavioral patterns based on problem characteristics. This transforms comparison knowledge into an actionable selection process.
You now have a comprehensive understanding of how behavioral patterns compare across multiple dimensions. This foundation enables systematic pattern selection based on problem analysis rather than intuition alone.