Behavioral
How objects interact and how responsibilities are distributed.
Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Their focus is on communication: who talks to whom, when, and under what contract.
#Why they are the most used in practice
Most of the code written today is more interested in flows than in structures: an event triggering a handler, a strategy chosen at runtime, a state machine changing an object's behavior. Behavioral patterns are the natural language to describe all of this.
#When they fit
- The same input can be processed in multiple ways depending on the context (
Strategy). - You want to decouple a message's sender from its receiver (
Observer,Mediator). - An operation involves several steps that can be canceled or passed to the next (
Chain of Responsibility). - An object's behavior depends on its internal state (
State). - You want to encapsulate an action to undo it, queue it, or audit it (
Command).
#When NOT to use them
- Visitor only pays off if the hierarchy is stable and operations change often.
- Mediator can become a God class if you don't set limits.
- Observer without explicit order explains 80% of "this fires twice" bugs.
#In this chapter
The 11 classics: Chain of Responsibility, Command, Iterator, Mediator,
Memento, Observer (with its reactive variant), State, Strategy,
Template Method, and Visitor.
- Chain of Responsibility — Passes a request along a chain of handlers until one processes it.
- Command — Encapsulates a request as an object, allowing parameterization, queuing, logging, and undo operations.
- Iterator — Traverse the elements of a collection without exposing its internal representation.
- Mediator — Defines an object that encapsulates how a set of objects interact, reducing coupling between them.
- Memento — Captures and externalizes an object's internal state without violating its encapsulation.
- Observer — Defines a one-to-many dependency so that multiple objects are notified when one changes.
- State — Allows an object to alter its behavior when its internal state changes; it will appear to change its class.
- Strategy — Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
- Template Method — Defines the skeleton of an algorithm in a base class, deferring some steps to subclasses.
- Visitor — Allows adding new operations to object structures without modifying their classes.
- Pipeline — Processes a request through handlers that progressively apply transformations or enrichments.