Chain of responsibility
medium 45 minA request travels past several handlers until one takes it, or until one stops it.
Watch lesson4:36
Against other patterns
Decorator, Strategy, Command, Observer, Composite, and a map.
The point: the structure is often the same. The question is who is allowed to stop.
| Chain of responsibility | The other | Tell them apart | |
|---|---|---|---|
| Decorator | A link may stop the request | A layer adds something and always delegates | May it refuse? Then it is a chain |
| Strategy | The request finds its handler | Somebody picks one algorithm before | Who chooses? |
| Command | Who does it is open | What is done is an object | They combine: a command travels a chain |
| Observer | Usually one takes it, order matters | All are told, order must not matter | How many react? |
| Composite | A line | A tree | Parents as next: bubbling |
| State | Many are asked | One current state answers | Is there a current one? |
| Map of handlers | Rules, may overlap | Keys, never overlap | Is there one key? |
Closest relative
Decorator and middleware
Wrapping middleware sits between the two. Logging only adds and always calls the next: a decorator. Authentication may stop: a chain. Frameworks use one interface for both, and both names are defensible. Say what your link may do instead of arguing about the name.
Four questions
Good combinations
- Template method in the base handler
- Composite parents as the chain
- Commands as requests, so that they can be queued after the chain
- A factory that builds the chain from configuration
Often confused
- A pipeline in which each stage changes the data and nobody stops: that is a plain pipeline
- Nested ifs moved into classes without any second list
- An event bus: everyone listens