AlgoViz

Chain of responsibility

medium 45 min

A 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 responsibilityThe otherTell them apart
DecoratorA link may stop the requestA layer adds something and always delegatesMay it refuse? Then it is a chain
StrategyThe request finds its handlerSomebody picks one algorithm beforeWho chooses?
CommandWho does it is openWhat is done is an objectThey combine: a command travels a chain
ObserverUsually one takes it, order mattersAll are told, order must not matterHow many react?
CompositeA lineA treeParents as next: bubbling
StateMany are askedOne current state answersIs there a current one?
Map of handlersRules, may overlapKeys, never overlapIs 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