Mediator pattern
medium 45 minThe 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
Mediator
1:03Reel
More reels
One idea each, a minute or less.
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
1993
RFC 1459 describes Internet Relay Chat in May: people talk in channels, through servers, and not to each other's addresses.
1994
The book Design Patterns is published on 31 October and lists Mediator among the behavioral patterns.
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.
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.
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.
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)The design that hurts
1/3Two fields
Each field asks the other one, so they hold references in both directions.
uses
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
1/4The contract
One method: something happened, and I am the one it happened to.
usesimplementsextends (is a)has (lives on)
A message through the middle
Build it in five steps
- 1
Contract
Declare how colleagues report:
notify, or better, one method for each kind of event. - 2
Concrete mediator
Write the rules between the colleagues, and nothing else.
- 3
Colleague base
One field for the mediator. No references to others.
- 4
Concrete colleagues
Each does its own work and reports what happened.
- 5
Wiring
Somebody creates the mediator and the colleagues and registers them.
Numbers
How many links really
Links between n objects
| Objects | Web, links | Star, links | Verdict |
|---|---|---|---|
| 2 | 1 | 2 | The star is worse |
| 3 | 3 | 3 | A draw |
| 4 | 6 | 4 | The star wins a little |
| 10 | 45 | 10 | Clear |
| 100 | 4,950 | 100 | No discussion |
Style
How colleagues report
| Way | Looks like | Good | Bad |
|---|---|---|---|
| One general method | notify(sender, event) | Small contract | A long if chain, misspelled event names |
| One method for each event | textChanged(field), clicked(button) | The compiler checks | The contract grows |
| Events as objects | handle(MessageSent(...)) | Can be stored, queued, logged | More classes |
| Callbacks or observers | field.onChange = ... | The colleague does not even know a mediator type | Harder to follow in a debugger |
Is the middle doing too much?
Neighbours
Which pattern is it
| Pattern | Its idea | Difference |
|---|---|---|
| Observer | One tells many that something happened | The subject does not coordinate. A mediator knows the parts and decides what they do |
| Facade | A simple front for a subsystem | One direction: the subsystem does not know the facade. Colleagues do know the mediator |
| Chain of Responsibility | A request goes along until one handles it | No middle: each handler decides alone. A mediator decides for all |
| Command | A request as an object | Often the form in which colleagues talk to the mediator |
| Proxy | Stands in for one object | One object behind it, same interface |
| Event bus | Anybody publishes, anybody listens | The bus has no rules. It connects, but does not coordinate |
Choose
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
| Gain | Cost |
|---|---|
| Cooperation in one place | That place can become a god object |
| Colleagues are reusable and testable alone | One more call and one more class |
| New colleagues without changing old ones | The mediator usually learns about new kinds |
| The whole picture allows better decisions | If 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.