Behavioral patterns
How objects communicate and share responsibilities.
- 11patterns
- 83animated steps
- 66code examples
Behavioral patterns organize the exchanges between objects: who notifies whom, who decides, who executes. They avoid long chains of conditionals and direct dependencies between classes.
The patterns
- 13Chain of Responsibility
Pass a request along a chain of handlers: each one handles it, stops it, or forwards it to the next.
- 14Command
Turn a request into a standalone object: it can then be passed as a parameter, queued, logged or undone.
- 15Iterator
Traverse the elements of a collection without exposing its internal representation (list, tree, paginated APIโฆ).
- 16Mediator
Reduce chaotic dependencies between objects by forcing them to communicate through a central mediator object.
- 17Memento
Capture and later restore an object's internal state without violating its encapsulation.
- 18Observer
Define a subscription mechanism to automatically notify several objects of a state change.
- 19State
Let an object change its behavior when its internal state changes, as if it had changed class.
- 20Strategy
Define a family of interchangeable algorithms and let you choose which one to use at runtime.
- 21Template Method
Define the skeleton of an algorithm in a base class, letting subclasses override certain steps without changing its structure.
- 22Visitor
Separate an algorithm from the object structure it operates on, so you can add operations without modifying those classes.
- 23Interpreter
Define the grammar of a small language and an interpreter that evaluates sentences in that language.
At a glance
| Pattern | Also known as | Use it for |
|---|---|---|
| Chain of Responsibility | โ | HTTP middlewares (Laravel, Express, ASP.NET, Go) |
| Command | Action | Undo / redo, action history |
| Iterator | Cursor | Complex collections (trees, graphs) |
| Mediator | โ | Tightly interconnected components (forms, UI) |
| Memento | Token | Undo / redo, save points |
| Observer | Publish-Subscribe | Domain events (OrderPaidโฆ) |
| State | Objects for States | State machines: orders, payments, workflows |
| Strategy | Policy | Several variants of the same algorithm |
| Template Method | โ | Algorithms with a fixed structure and variable steps |
| Visitor | โ | Stable structure, operations added frequently |
| Interpreter | โ | Simple DSLs: business rules, filters, formulas |
Other families
-
Creational patterns
5 patterns
How to create objects flexibly, without coupling your code to concrete classes.
-
Structural patterns
7 patterns
How to assemble classes and objects into larger structures that stay flexible.