AlgoViz

Mediator pattern

medium 45 min

The Mediator pattern puts the rules of how a group of objects works together into one object in the middle.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:27

Mediator

1:03Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Observer vs mediator

0:32Reel

Theory

Read or listen first. About 2 min.

What it is

The Mediator pattern is a behavioral design pattern. A mediator contains the interaction of a set of colleagues. Colleagues hold a reference to the mediator and to no other colleague.

The shape of the references changes from a web, many to many, to a star, many to one and one to many. A colleague reports what happened to it, the mediator decides what others should do.

The colleagues do not lose their work. A text field still validates its text, a flight still flies. Only the questions that concern several of them move to the middle.

Why it exists

Without it, the cooperation is spread over all parts. Nobody can read it, each part drags its neighbours along, and a new part changes the old ones.

With it, the cooperation is a class. It can be read, tested with fakes, replaced by another, and extended by new colleagues.

It matters most where rules join several objects: dialogs, chat rooms, scheduling one resource, workflows over several services.

A short history

  1. 1993

    RFC 1459 describes Internet Relay Chat in May: people talk in channels, through servers, and not to each other's addresses.

  2. 1994

    The book Design Patterns is published on 31 October and lists Mediator among the behavioral patterns.

  3. JDK 1.2

    Swing's ButtonGroup arrives: buttons do not know each other, the group keeps only one switched on.

Words to know

Mediator
The object in the middle, or its interface.
Colleague
An object that cooperates through the mediator.
Star
One center, and one link to each part.
Coordination
Who acts when, because another one changed.
God object
A class that knows and does too much.
Echo
A report caused by the mediator's own update.
Run to completion
One event is handled fully before the next one starts.
Event bus
Connects publishers and listeners without rules between them.
Orchestration
One service tells the others what to do.
Choreography
Services react to each other's events without a center.
Back pressure
What happens when a receiver is slower than the sender.
Wiring
Creating the objects and connecting them.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Report. A colleague tells the mediator what happened

Understand it

Start here

One guide, many dancers

Some objects have to act together. If each of them talks to each other one, the rules of acting together are spread over all of them. The Mediator pattern moves these rules into one object in the middle. Everybody talks to the middle, and nobody talks to a neighbour.

Asha and the dancing tugboats

The boats still sail themselves. Asha only decides who goes when.

The four roles

  • Mediator

    The contract: how colleagues tell the middle what happened.

  • Concrete mediator

    Knows the colleagues and the rules between them: ChatRoom, AuthDialog, ControlTower.

  • Colleague

    Knows the mediator and no other colleague. Often a small base class.

  • Concrete colleagues

    Do their own work and report: ChatUser, TextInput, Flight.

Why

What goes wrong without it

A login window has two fields and a button. The first version is direct: a field enables the button. It is only a line. Then a checkbox arrives.

Python
class Field:    def __init__(self):        self.text, self.others, self.button = "", [], None    def type(self, text):        self.text = text        if all(len(f.text) > 0 for f in [self, *self.others]):   # rule, copy 1            self.button.enabled = True        else:            self.button.enabled = Falseclass Terms:                              # added one month later    def __init__(self, name, button):        self.name, self.button, self.on = name, button, False    def tick(self):        self.on = not self.on        self.button.enabled = self.on and self.name.text != ""   # rule, copy 2class Button:    enabled = Falsebutton, name, password = Button(), Field(), Field()name.others, password.others = [password], [name]name.button = password.button = buttonterms = Terms(name, button)name.type("asha")terms.tick()print("enabled without a password:", button.enabled)
Run it. Each field repeats the rule, and the checkbox forgot the password.
Edit and run it in your browser

The design that hurts

Username+ typed(): rulePassword+ typed(): rule

1/3Two fields

Each field asks the other one, so they hold references in both directions.

uses

The smell: a small part that can not be created without three others.

Everybody knows the middle

  • The rule is in one class
  • Parts can be used in any window
  • A new part joins the middle
  • The cooperation can be read and tested

Everybody knows everybody

  • The rule is copied
  • A part can not be reused alone
  • A new part changes the old ones
  • Nobody sees the whole cooperation

The idea

From a web to a star

The Mediator pattern in general

«interface»Mediator+ notify(sender, event)

1/4The contract

One method: something happened, and I am the one it happened to.

usesimplementsextends (is a)has (lives on)

Dependencies go both ways between middle and colleagues: upwards through an interface, downwards to what the rules need.

A message through the middle

Alice never calls Bob. Bob learns the name Alice as text in the message, if the room decides to include it.

Build it in five steps

  1. 1

    Contract

    Declare how colleagues report: notify, or better, one method for each kind of event.

  2. 2

    Concrete mediator

    Write the rules between the colleagues, and nothing else.

  3. 3

    Colleague base

    One field for the mediator. No references to others.

  4. 4

    Concrete colleagues

    Each does its own work and reports what happened.

  5. 5

    Wiring

    Somebody creates the mediator and the colleagues and registers them.

Numbers

How many links really

Links between n objects

web: n(n−1)2star: n\text{web: } \frac{n(n-1)}{2} \qquad \text{star: } n
A link is a pair that knows each other, so it is two references. Web: n(n-1) references. Star: 2n, because the middle also holds its colleagues.
ObjectsWeb, linksStar, linksVerdict
212The star is worse
333A draw
464The star wins a little
104510Clear
1004,950100No discussion
Compare links with links. Comparing n(n-1) references with n links makes the star look better than it is. The stronger argument is not the count anyway: it is that the rules have one home.

Style

How colleagues report

WayLooks likeGoodBad
One general methodnotify(sender, event)Small contractA long if chain, misspelled event names
One method for each eventtextChanged(field), clicked(button)The compiler checksThe contract grows
Events as objectshandle(MessageSent(...))Can be stored, queued, loggedMore classes
Callbacks or observersfield.onChange = ...The colleague does not even know a mediator typeHarder to follow in a debugger
The last way is common in user interfaces: the dialog observes its widgets. Mediator says who decides, Observer is one way to hear about changes.

Is the middle doing too much?

Validation of one field is the job of the field. Whether the button lights up depends on several, so it belongs to the middle.

Neighbours

Which pattern is it

PatternIts ideaDifference
ObserverOne tells many that something happenedThe subject does not coordinate. A mediator knows the parts and decides what they do
FacadeA simple front for a subsystemOne direction: the subsystem does not know the facade. Colleagues do know the mediator
Chain of ResponsibilityA request goes along until one handles itNo middle: each handler decides alone. A mediator decides for all
CommandA request as an objectOften the form in which colleagues talk to the mediator
ProxyStands in for one objectOne object behind it, same interface
Event busAnybody publishes, anybody listensThe bus has no rules. It connects, but does not coordinate

Choose

If the middle contains no rule, it is only a detour.

Use it when

  • Objects cooperate in complicated ways
  • A part can not be reused because it knows too many
  • The cooperation should change without new part classes
  • You want to test the rules alone

Leave it when

  • Two or three objects with one simple call
  • The middle would contain no decision
  • The middle would contain everything
  • A measured hot path can not pay for one more call

A form has eight fields that influence each other. Where do the rules go?

BreaksInto the fields
How
Each field updates the others.
Limit
Up to 28 pairs, rules in eight places, and loops nobody sees.
Choose when
Never with eight.
WorksEvents on a bus
How
Fields publish, fields listen.
Limit
No references, but the rules are still in eight places, and the order is unclear.
Choose when
Parts that react independently.
StrongOne mediator
How
Fields report to the form, the form decides.
Limit
The form grows. Split it by section when it does.
Choose when
Rules that join several fields.

Gains and costs

GainCost
Cooperation in one placeThat place can become a god object
Colleagues are reusable and testable aloneOne more call and one more class
New colleagues without changing old onesThe mediator usually learns about new kinds
The whole picture allows better decisionsIf the middle fails, all wait

Summary

The whole topic in one minute.

Colleagues report facts, the mediator decides, colleagues do the work. The missing arrows between colleagues are the pattern.

Count honestly: links against links, a draw at three. The real gain is that rules between objects have one home that can be tested.

In production: thin middle, one event at a time, a bounded queue for each receiver, guards against echoes, and a plan for the day when the middle is gone.

  • Many to many becomes many to one. The missing arrows are the pattern.
  • Colleagues report facts. The mediator decides. Colleagues do the work.
  • Compare links with links: a draw at three, 45 against 10 at ten.
  • Keep it thin. Coordination in, calculations out.
  • Guard against echoes, races and colleagues that never leave.
  • Two objects and one call need no mediator.

Sources