Card 03/ 05

ComparisonDifficulty: Intermediate2 min

Observer vs Mediator and Chain of Responsibility vs Decorator

Two pairs that share a shape: many listeners or one coordinator, and passing on or wrapping.

Two more pairs are often confused, each because the two patterns move a call between objects in a similar way. Observer and Mediator both stop objects referring to each other directly, and they differ in whether anything decides what happens next. Chain of Responsibility and Decorator both line objects up behind one interface, and they differ in whether every object passes the call on. This card gives each pair its table and its two sequence diagrams.

Observer and Mediator side by side
QuestionObserverMediator
Who reacts to a change?Every subscriber, each deciding for itselfThe mediator, which decides for all
Does the sender know the receivers?No; it notifies whoever subscribedNo; it tells the mediator
Where is the logic of who does what?Spread across the subscribersIn the mediator
Direction of communicationOne to many, outwardMany to one, then one to many
Observer: the subject notifies every subscriber
Mediator: a field tells the dialog, which decides

The question for this pair is: after the change, does one object decide what everyone else does? If yes, it is a mediator. If each listener decides for itself what the change means to it, it is an observer. A mediator often uses observer notifications to hear about changes, which is why the two appear together.

Chain of Responsibility and Decorator side by side
QuestionChain of ResponsibilityDecorator
Does every object pass the call on?No; a handler may stop the chainYes; each calls the object it wraps
How many objects do the work?Usually one, the first that canAll of them, each adding a layer
What if nothing handles it?It falls off the end of the chainNot possible; the innermost object always runs
FamilyBehaviouralStructural
Chain of Responsibility: the second handler stops the call
Decorator: every layer passes the call on

The question for this pair is: can an object in the line stop the call? If it can, and the point is to find the one that handles it, it is a chain; the director never sees the £800 request. If every object passes the call on and the point is the combined layers, it is a decorator. Web middleware sits between the two: each layer can stop a request, as a chain does, and most pass it on with something added, as a decorator does.