At a busy airport, pilots don't phone each other to decide who lands first. Each pilot only talks to the control tower, and the tower decides who lands, who waits, and which runway is used. A plane that just arrived only needs the tower's frequency, not the number of every other plane.
The Mediator pattern puts a tower like that in your code: one object in the middle that handles the communication between several objects, so they don't call each other directly. Each object only knows the go-between (the mediator), and the mediator knows who has to react when something happens.
The problem: components that know each other
On the dispatch screen, picking courier Budi must filter the parcel list to Budi's parcels and draw his route on the map. Picking a parcel, in the list or through a pin on the map, must light up its courier. The first version wrote all that in each component's click method:
// the click part of the three components
const courierList = {
click(name) {
this.highlight(name)
parcelList.filter(name) // knows parcelList
map.route(name) // knows map
},
}
const parcelList = {
click(trackingNo) {
const courier = find(trackingNo).courier
courierList.highlight(courier) // knows courierList
this.filter(courier)
this.highlight(trackingNo)
map.route(courier) // knows map
map.mark(trackingNo)
},
}
const map = {
click(trackingNo) {
const courier = find(trackingNo).courier
courierList.highlight(courier) // knows courierList
parcelList.filter(courier) // knows parcelList
parcelList.highlight(trackingNo)
this.route(courier)
this.mark(trackingNo)
},
}
Each component knows the other two: their object names and their method names. That's 6 call links for 3 components. The rule "picking a parcel moves to its courier" is written twice, in parcelList and in map. The parcel list also can't be tested or used on another screen without bringing courierList and map along.
Mediator: one centre that coordinates
const PARCELS = [
{ trackingNo: "KCL-0001", courier: "Andi", kg: 2, area: "Eastfield" },
{ trackingNo: "KCL-0002", courier: "Budi", kg: 1, area: "Hillside" },
{ trackingNo: "KCL-0003", courier: "Andi", kg: 4, area: "Oakwood" },
{ trackingNo: "KCL-0004", courier: "Citra", kg: 3, area: "Riverside" },
{ trackingNo: "KCL-0005", courier: "Budi", kg: 5, area: "Northgate" },
{ trackingNo: "KCL-0006", courier: "Citra", kg: 2, area: "Parkview" },
]
const ownedBy = (name) => PARCELS.filter((p) => p.courier === name)
const find = (trackingNo) => PARCELS.find((p) => p.trackingNo === trackingNo)
function createDispatch() {
const parts = {}
function selectCourier(name) {
parts.courier.highlight(name)
parts.parcel.filter(name)
parts.map.route(name)
}
return {
register(name, part) {
parts[name] = part
part.dispatch = this
},
notify(from, event, data) {
console.log("dispatch ← " + from + ": " + event + " " + data)
if (event === "courierSelected") selectCourier(data)
if (event === "parcelSelected") {
selectCourier(find(data).courier)
parts.parcel.highlight(data)
parts.map.mark(data)
}
},
}
}
const courierList = {
click(name) { this.dispatch.notify("courierList", "courierSelected", name) },
highlight(name) { console.log("courierList: highlight " + name) },
}
const parcelList = {
click(trackingNo) { this.dispatch.notify("parcelList", "parcelSelected", trackingNo) },
filter(name) { console.log("parcelList: show parcels of " + name + ": " + ownedBy(name).map((p) => p.trackingNo).join(", ")) },
highlight(trackingNo) { console.log("parcelList: highlight " + trackingNo) },
}
const map = {
click(trackingNo) { this.dispatch.notify("map", "parcelSelected", trackingNo) },
route(name) { console.log("map: route " + name + " via " + ownedBy(name).map((p) => p.area).join(", ")) },
mark(trackingNo) { console.log("map: mark " + trackingNo) },
}
const dispatch = createDispatch()
dispatch.register("courier", courierList)
dispatch.register("parcel", parcelList)
dispatch.register("map", map)
createDispatch()makes the mediator.partsholds the registered components, and only the mediator holds it.registersigns a component up and gives itpart.dispatch, the only other object it knows.- Every
clickis now one line:this.dispatch.notify(from, event, data). The component reports what happened ("courierSelected"), it doesn't order other components around. notifyholds the coordination rules. "Picking a parcel moves to its courier" is now written once, inselectCourier, and used for a click in the parcel list as well as on the map.highlight,filter,routeandmarkonly change their own component's view. They don't know other components exist.
One click, traced
parcelList.click("KCL-0004")
// dispatch ← parcelList: parcelSelected KCL-0004
// courierList: highlight Citra
// parcelList: show parcels of Citra: KCL-0004, KCL-0006
// map: route Citra via Riverside, Parkview
// parcelList: highlight KCL-0004
// map: mark KCL-0004
The parcel list calls one method, notify. The mediator finds the courier who owns KCL-0004 (Citra), then tells all three components to react. What the screen shows is exactly the same as the call-each-other version. The only thing that changed is who knows the rules.
The fourth panel: who has to change
Now the dispatch screen gets a fourth component: a courier workload summary panel, which has to update every time a courier or a parcel is picked. Take a guess first: how many old components have to change in the call-each-other version, and how many in the mediator version?
In the call-each-other version, the summary panel means adding summary.count(...) to the click of courierList, parcelList and map: 3 old components edited, and the links grow from 6 to 9. In the mediator version, 0 old components are edited: just dispatch.register("summary", summary) and one parts.summary.count(name) line in selectCourier.
When every component can tell all the others, the number of links is n × (n − 1): 3 components have 6 links, 4 have 12, and 10 have 90. Through a mediator, each component knows only one: 10 components, 10 links.
Mediator or Pub/Sub?
Both have a centre in the middle, but the centre plays a different role:
| Mediator | Pub/Sub | |
|---|---|---|
| the centre | knows every component and the coordination rules | a broker that only forwards messages per topic |
| logic | in the mediator ("picking a parcel lights up its courier") | in each subscriber; the broker has none |
| the sender | knows its mediator | doesn't know who subscribes |
| example | the dispatch screen, a checkout form, a dialog | a warehouse announcing "parcel in transit" to other services |
Stores like Redux, Zustand or Pinia also work like a mediator: components send actions to the store, and the store updates the state and then tells the components that need it.
A mediator that grows too fat
A mediator gathers the rules in one place, and that's its risk too. An app-wide mediator with thousands of lines that knows every component's details (its CSS classes, the elements inside it) is called a God class: every new feature edits the same file, and one mistake can break everything. Split it by need, say one mediator for the dispatch screen and one for the checkout form, and have it tell components what to do through methods whose names say the intent (highlight, filter), not by fiddling with their insides.
Exercise: a form with a mediator
The exercise uses a simpler version for a form. createFormMediator() returns an object with five methods, and its mediator sends every event to all registered handlers. The rules live in the handlers.
register(name, handler): keep the handler, in aMapfor example. A handler is called ashandler(event, mediator).setField(name, value): store it infields[name], make the event{ type: "fieldChanged", name, value }, keep the event in the log, then call every handler.getField(name): returnfields[name].submit(): make the event{ type: "submit", fields: { ...fields } }, keep it in the log, then call every handler.log(): return the array of every event, in the order they happened.
The starter registers a validator handler that records invalid or valid for the email field (whether it has an @) and submitted: plus the number of fields on submit. The console then shows invalid, valid, [email protected], Budi, submitted:2 and 4 (three setField calls and one submit). Also graded: two registered handlers both receive one event, and a handler named city receives fieldChanged and then submit.
⚠️ A hub that leaks, bloats or bounces
- One direct call "just this once". As soon as
mapcallsparcelListdirectly, the coordination rules scatter again, and a new panel means editing old components. - A mediator that becomes a God class. Thousands of lines that know the inside of every component. Split it per screen or per form.
- An echo that never ends. A method the mediator calls (
highlight) callsnotifyagain, and the program stops withRangeError: Maximum call stack size exceeded. Only user actions, like a click, tell the mediator. - In the exercise: calling only the handler named like the field. Every handler must be called for every event, and
submitgoes into the log too, solog().lengthcomes to 4.
TL;DR: Mediator puts one centre in the middle: components only report to the mediator (this.dispatch.notify("parcelList", "parcelSelected", trackingNo)), and the mediator knows who has to react. Without a mediator, n components that know each other can have n × (n − 1) links (10 components, 90 links); with one, n links. A fourth panel on the dispatch screen edits 3 old components in the call-each-other version, and 0 in the mediator version. The difference from Pub/Sub: a mediator knows its components and holds rules, a broker only forwards messages. Don't let a mediator become a God class, and don't let a method the mediator calls tell it again. In the exercise: setField and submit log the event and then call every handler, and log() returns every event in order.
⚡ Components that know each other
Meaning: Each component on the dispatch screen knows the other two: their object names and their method names. 3 components already make 6 call links. When every component can tell all the others, the number is n × (n − 1): 10 components make 90 links.
⚡ One centre that coordinates
Write:
notify(from, event, data) {
console.log("dispatch ← " + from + ": " + event + " " + data)
if (event === "courierSelected") selectCourier(data)
if (event === "parcelSelected") {
selectCourier(find(data).courier)
parts.parcel.highlight(data)
parts.map.mark(data)
}
},
Meaning: The mediator becomes the centre of coordination. Components only report what happened through notify, and the mediator knows who has to react. Through a mediator, each component knows only one: 10 components, 10 links.
⚡ The fourth panel
Guess first: the dispatch screen gets a courier workload summary panel. How many old components change in the call-each-other version, and in the mediator version?
3 in the call-each-other version, 0 in the mediator version: just dispatch.register("summary", summary) and one line in selectCourier.
Meaning: The difference from Pub/Sub: a mediator knows its components and holds rules, a broker only forwards messages. Don't let a mediator become a God class: split it per screen.