Mediator puts one object, the mediator, in the middle of a group of objects that would otherwise call each other directly. The objects, called colleagues, stop holding references to one another: each reports to the mediator when something happens, and the mediator decides who reacts and how. A tangle of many-to-many links becomes one-to-many links around a hub, and the rules for how the group behaves live in one class instead of being spread over all of them.
Think of it like
An airport control tower
Pilots approaching a busy airport do not negotiate with each other about who lands first; with dozens of aircraft that would be chaos. Each pilot talks only to the tower, and the tower knows every aircraft, the runways and the rules, so it decides who lands, who holds and who taxis. A new aircraft joining the pattern needs one radio frequency, not a conversation with every plane already there. The tower is the mediator, the aircraft are colleagues, and the radio calls are the notifications.
The problem
A checkout form has three widgets. A Checkbox says "ship to my billing address", an AddressField takes a shipping address, and a SubmitButton must be enabled only when the form can be sent: the box is ticked, or an address is typed. Ticking the box also disables the address field. The direct way is to let each widget update the others itself. This is the Before version in the visualizer above.
class AddressField {
value = "";
enabled = true;
ship!: Checkbox; // set later: the checkbox needs this field first
constructor(private btn: SubmitButton) {}
type(text: string) {
this.value = text;
this.btn.setEnabled(this.ship.checked || this.value !== "");
}
setEnabled(on: boolean) { this.enabled = on; }
}
class Checkbox {
checked = false;
constructor(private addr: AddressField, private btn: SubmitButton) {}
toggle() {
this.checked = !this.checked;
this.addr.setEnabled(!this.checked);
// the same rule as in AddressField.type(), copied
this.btn.setEnabled(this.checked || this.addr.value !== "");
}
}
const btn = new SubmitButton();
const addr = new AddressField(btn);
const ship = new Checkbox(addr, btn);
addr.ship = ship; // close the loop by handIt works, and with three widgets it is still readable. The costs grow with every widget and every rule:
- Every widget knows the others' concrete classes. Three widgets already hold four references to each other, two of them pointing both ways. When every widget interacts with every other, n widgets need up to n × (n − 1) references.
- The rules are scattered and copied. "The button is enabled when the box is ticked or an address is typed" is written in
AddressField.type()and inCheckbox.toggle(). Change one and forget the other, and the form behaves differently depending on which widget the user touched last. - No widget is reusable.
AddressFieldcannot go on another form without draggingCheckboxandSubmitButtonalong, because it calls them by name. - Construction order turns into a puzzle. The field reads the checkbox and the checkbox calls the field, so one of the two references has to be patched in after both exist.
- Every new widget edits the old ones. A note showing where the order ships must be updated by both the checkbox and the field, so both classes change (the change request in the visualizer).
The pattern
Intent: define an object that encapsulates how a set of objects interact. Mediator keeps the objects from referring to each other explicitly, which keeps them loosely coupled and lets you change how they interact without changing them.
- Mediator (
Mediator) - The interface colleagues talk to, often one method such as
changed(src)(the Gang of Four call itWidgetChanged) ornotify(sender, event). Colleagues depend on this interface only, not on the class that implements it. - Concrete mediator (
CheckoutForm) - Knows every colleague and holds the coordination rules: when
srcis the checkbox, disable or enable the field; after any change, re-check the button. Here it also builds the widgets, so it owns them (composition in the class diagram). - Colleague (
Checkbox,AddressField) - A participant that does its own job (keep a value, toggle a flag) and reports changes to its mediator, held in a
dialogfield. It never calls another colleague. - Receive-only colleague (
SubmitButton,ShippingNote) - A participant the mediator only calls. It never reports anything, so it needs no reference to the mediator at all.
- Client
- Creates the mediator, which wires up the colleagues. In the visualizer the client stands in for the user: it types into the field and ticks the box.
The pattern is often summed up as "many-to-many becomes one-to-many". Count references when every colleague interacts with every other: direct links need one per ordered pair, while with a mediator each colleague points to the hub and the hub points back.
| Colleagues that all interact | Direct references, n × (n − 1) | With a mediator, 2n |
|---|---|---|
| 3 | 6 | 6 |
| 5 | 20 | 10 |
| 10 | 90 | 20 |
What the visualizer shows
Press Play in the visualizer at the top of the page, or step through it with the arrow buttons. It really runs the classes in the code panel and draws what happened. The running line is highlighted, and the caption under the stage explains every step.
- The tangle (Before): in the class diagram,
CheckboxandAddressFieldpoint at each other and both point atSubmitButton. In the Objects view,shipandaddrhold arrows to each other and tobtn, and the messages go straight from widget to widget (shipcallsaddr.setEnabled(false)). - The hub (With Mediator):
Mediatorsits on top with an arrow from each talking widget and the implements line fromCheckoutForm; the form's composition diamonds point down to every widget. In the Objects viewformis in the middle,ship.dialogandaddr.dialogpoint to it, andbtnpoints nowhere. - Sequence of calls: with Mediator every reaction is a staircase through the hub:
addrcallschanged(addr)onform, and only then doesformcallsetEnabledonbtn. No message ever goes from one widget lane to another. - Before / With Mediator and Add shipping note: the toggle switches between the versions; Add shipping note applies the change request. Changed classes get a badge in the class diagram, and the Change request panel beside the code compares what each version had to change. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Build the form
With With Mediator selected, the client creates only
form. Its constructor createsshipandaddr, passing itself, so each storesdialog = form. It createsbtnwithout a mediator, because the button only displays a state. At the endformholdsship,addrandbtn, and no widget holds another widget. - 2
The user types an address
The client calls
addr.type("12 Elm St"). The field stores the value and callsthis.dialog.changed(this): it reports that it changed and decides nothing else. - 3
The mediator decides
changed(addr)runs inCheckoutForm(the call is declared by theMediatorinterface, which lights up violet). The sender is not the checkbox, so the form skips the line that disables the field. It then applies the one copy of the button rule and callsbtn.setEnabled(true). - 4
The user ticks the box
ship.toggle()setschecked = trueand reportschanged(ship). This time the sender is the checkbox, so the form callsaddr.setEnabled(false), thenbtn.setEnabled(true). One event, two reactions, both chosen by the form. - 5
Compare with Before
Switch to Before: the same two user actions produce the same final state, but
addrcallsbtnandshipcallsaddrandbtndirectly, and the button rule runs from two different classes. - 6
Add the shipping note
With Add shipping note applied, the form builds a
noteand adds one call tochanged():note.show(c ? "billing" : this.addr.value). Typing shows"12 Elm St", ticking shows"billing", andCheckboxandAddressFieldare the same code as before.
Before and after
Without the pattern
- Widgets hold references to each other's concrete classes
- The button rule is written in two widgets
- A reference loop has to be closed by hand after construction
- A new widget edits every widget that affects it
- No extra class; each widget's code shows what it triggers
With Mediator
- Widgets hold only the
Mediatorinterface, or nothing - Every rule lives in
CheckoutForm.changed() - The mediator builds the widgets, so there is no loop to patch
- A new widget edits only the mediator
- One more class, and it grows with every rule: watch its size
| Change request: add a shipping note | Before | With Mediator |
|---|---|---|
| Existing classes edited | 2 (Checkbox, AddressField) | 1 (CheckoutForm) |
| New classes | 1 (ShippingNote) | 1 (ShippingNote) |
| Lines changed in existing classes | 11 (+9 −2) | 4 (+4 −0) |
| Classes touched | 3 | 2 |
Both versions need the new ShippingNote class. The difference is who has to learn about it. Before, both widgets that can change the note get a new constructor parameter, a new field and a call to note.show(...) with its own copy of the text rule, and the client passes the note to both. With Mediator, the form gets a field, one line in its constructor and one call in changed(); the widgets are untouched and still do not know the note exists. The reference count tells the same story: before, the note adds two more widget-to-widget references (4 becomes 6); with the mediator it adds one, from the hub.
Variations
How colleagues talk to the mediator
- One method with the sender, as in the visualizer and the Gang of Four's
WidgetChanged(widget): the mediator compares the sender with its fields. Simple, but the mediator must work out what changed. - Sender plus an event name:
notify(this, "ticked"). The mediator switches on the event. Common in tutorials; string names are easy to mistype, so prefer an enum or a union type. - One method per event:
addressTyped(text),shippingToggled(on). The most explicit and type-safe; the mediator interface grows with every event. - Events instead of calls: the colleagues are plain observable objects that raise events, and the mediator subscribes to them. Colleagues then do not even know a mediator exists, which is how most UI frameworks wire a dialog controller to its widgets. This is Mediator built on top of Observer.
Mediator with events, and event buses
An in-process event bus ("publish cart:changed, anyone may subscribe") is often called a mediator, and it does give the same decoupling: senders and receivers only know the bus. But a plain bus holds no rules; it is a broker, which makes it Publish/Subscribe. What makes something a Mediator is that the hub contains the coordination logic: it knows the participants and decides who reacts. Many real designs mix the two, for example a bus for transport and a coordinator object that subscribes to it and drives the others.
With or without an abstract mediator
The Gang of Four note that the abstract Mediator can be dropped when colleagues only ever work with one mediator; colleagues then hold the concrete class. Keep the interface when the same widgets appear in several dialogs, or when you want to test a colleague with a fake mediator that just records changed() calls. It also keeps the dependency honest: a colleague can report changes but cannot reach into the form's other widgets.
In real code
| Where | The mediator | The colleagues |
|---|---|---|
| The Gang of Four book | FontDialogDirector, a subclass of DialogDirector, whose WidgetChanged() reacts to each widget | The dialog's list box, entry field and buttons; the visualizer's form is the same idea |
| Java Swing | ButtonGroup: selecting one button in the group deselects the others | JRadioButtons (any AbstractButton) added with group.add(button); they never reference each other |
| HTML forms | The browser enforces that one radio button per name is checked | <input type="radio"> elements that share a name |
| .NET MediatR library | IMediator: Send(request) goes to exactly one handler, Publish(notification) to every handler | Controllers and handlers that never reference each other. Closer to an in-process message bus than to the GoF dialog, but named after the pattern |
| UI controllers (MVC, MVVM) | A controller or view model that listens to the widgets of a screen and updates the others and the model | The views and widgets of that screen |
| Redux and similar stores | In general terms, the store is a hub: components dispatch(action) and reducers decide how state changes | Components, which never call each other to share state |
| Chat servers | The room or server routes each message: broadcast, direct, muted | Connected clients, which only know the server (the second implementation below) |
| Game engines | An event manager or game-mode object that coordinates entities (a trigger opens a door, a score update ends the round) | Entities and systems that report events instead of calling each other |
| Distributed systems | A message broker routes between services, and a workflow orchestrator (as in an orchestrated Saga) tells each service what to do next | Services that know the broker or orchestrator, not each other. See Message Queues & Pub/Sub |
Air traffic control is the classic real-world mediator (the analogy above), and the shape scales up: an orchestrated saga is a mediator for services, while choreography (each service reacting to the others' events, see Event-Driven Architecture, CQRS & Event Sourcing) is the many-to-many alternative. The trade-off is the same as in the form: one place that knows the whole flow, against a hub that every change goes through.
When to use it, and when not to
Reach for Mediator when
- Several peer objects interact in many directions and the links keep growing
- Interaction rules are duplicated across the participants
- You want to reuse a component in another context without its neighbors
- The behavior of a whole group (a dialog, a workflow, a room) should be readable in one place
- The same components must behave differently in different groups: swap the mediator
Think twice when
- Two or three objects interact in one direction: a direct call is clearer
- Receivers only need to hear that something happened: Observer is enough
- The mediator would only forward calls without any rules of its own
- The rules are domain logic that belongs in the objects themselves
- One mediator would end up coordinating unrelated parts of the system
Mediator is one way to apply the low-coupling advice in DRY, KISS, YAGNI & the Law of Demeter: each colleague talks to one collaborator instead of many, and the knowledge of who affects whom gets one home instead of being repeated in every class (the DRY problem in the Before version).
Mediator vs similar patterns
| Pattern | Who knows whom | Where the logic lives | Typical use |
|---|---|---|---|
| Mediator | Colleagues know only the mediator; the mediator knows every colleague | In the mediator: it decides who reacts | Peers with tangled two-way interactions: a dialog, a chat room, a control tower |
| Observer | The subject holds a list of observers behind an interface | In each observer: the subject only broadcasts that something happened | One source, any number of independent reactions |
| Facade | Clients know the facade; the subsystem does not know the facade exists | In the facade, but only to simplify calls into the subsystem, one way | A simple entry point to a complex subsystem |
| Chain of Responsibility | Each handler knows the next one | Spread over the handlers: each decides to handle or pass on | One request offered to handlers in turn: middleware, approvals |
| Publish/Subscribe broker | Publishers and subscribers know only the broker and topic names | In the subscribers; the broker only routes by topic | Decoupled delivery between modules or services, often asynchronous |
Implementation
The scenario as a complete program, with the shipping note included: a Mediator interface, a Widget base class that holds the mediator and reports changes, Checkbox and AddressField as talking widgets, SubmitButton and ShippingNote as display-only widgets, and CheckoutForm as the concrete mediator that builds the widgets and holds every rule. The demo types an address, ticks and unticks the box and clears the address, printing the form's state after each step. In C++ the widgets keep a reference to the form, so the form is made non-copyable.
from __future__ import annotations
from abc import ABC, abstractmethod
class Mediator(ABC):
"""The widgets know only this interface, never each other."""
@abstractmethod
def changed(self, src: Widget) -> None: ...
class Widget:
def __init__(self, dialog: Mediator) -> None:
self._dialog = dialog
def _tell(self) -> None:
self._dialog.changed(self)
class Checkbox(Widget):
def __init__(self, dialog: Mediator) -> None:
super().__init__(dialog)
self.checked = False
def toggle(self) -> None:
self.checked = not self.checked
self._tell()
class AddressField(Widget):
def __init__(self, dialog: Mediator) -> None:
super().__init__(dialog)
self.value = ""
self.enabled = True
def type(self, text: str) -> None:
self.value = text
self._tell()
def set_enabled(self, on: bool) -> None:
self.enabled = on
# Display-only widgets never report anything, so no mediator.
class SubmitButton:
def __init__(self) -> None:
self.enabled = False
def set_enabled(self, on: bool) -> None:
self.enabled = on
class ShippingNote:
def __init__(self) -> None:
self.text = ""
def show(self, text: str) -> None:
self.text = text
class CheckoutForm(Mediator):
"""The concrete mediator: builds the widgets, owns every rule."""
def __init__(self) -> None:
self.ship = Checkbox(self)
self.addr = AddressField(self)
self.btn = SubmitButton()
self.note = ShippingNote()
def changed(self, src: Widget) -> None:
same_as_billing = self.ship.checked
if src is self.ship:
self.addr.set_enabled(not same_as_billing)
self.btn.set_enabled(same_as_billing or self.addr.value != "")
self.note.show("billing" if same_as_billing else self.addr.value)
def describe(self) -> str:
def on(flag: bool) -> str:
return "on" if flag else "off"
return (
f"address {on(self.addr.enabled)}, "
f"submit {on(self.btn.enabled)}, "
f'ships to "{self.note.text}"'
)
if __name__ == "__main__":
form = CheckoutForm()
print(form.describe()) # address on, submit off, ships to ""
form.addr.type("12 Elm St")
print(form.describe()) # address on, submit on, ships to "12 Elm St"
form.ship.toggle()
print(form.describe()) # address off, submit on, ships to "billing"
form.ship.toggle()
form.addr.type("")
print(form.describe()) # address on, submit off, ships to ""Key takeaways
- Mediator replaces direct references between peer objects with references to one hub: colleagues report changes to the mediator, and the mediator decides who reacts.
- The coordination rules move into one class. In the visualizer the button rule, written twice in the Before version, exists once in
CheckoutForm.changed(). - Colleagues depend only on the
Mediatorinterface (or on nothing, if they only receive calls), so they can be reused and tested on their own. - For the "add a shipping note" request: with Mediator 1 existing class edited (4 lines), versus 2 classes and 11 lines without it.
- The price is a central class that grows with every rule. Keep it about coordination, and split it before it turns into a god object.
- Observer broadcasts and lets each listener decide; Mediator centralizes the decision. A pub/sub broker routes without rules; a facade simplifies one-way access to a subsystem.
Common pitfalls
- The god mediator: every rule of a large screen piles into one
changed()method that everybody edits. Split by area, and keep domain logic in the objects that own it. - Colleagues that still talk to each other "just this once", or reach through the mediator (
dialog.addr.setEnabled(false)): the tangle comes back, now with an extra hop. - Feedback loops: the mediator updates a colleague, the colleague reports the change, and the mediator reacts again. Only report user-driven changes, or ignore updates the mediator made itself.
- A mediator that only forwards calls without any logic: that is an extra layer with no benefit. Call the object directly, or use an event bus if decoupling is the only goal.
- Calling every pub/sub bus a mediator: if the hub holds no rules about who reacts, it is a broker, and the coordination logic is still spread over the subscribers.
Interview tips
- Draw the before and after link counts: n × (n − 1) possible references between peers versus 2n with a hub. Then say honestly that the real win is centralized rules and reusable colleagues, not the count at small n.
- Have a concrete example ready: a form or dialog where one widget enables another (the Gang of Four example), a chat room, or air traffic control. In LLD rounds (chat app, elevator controller, auction, smart home hub) a coordinator class is often a mediator; name it as one.
- Expect "Mediator vs Observer" and "Mediator vs Facade". Observer: the subject broadcasts and listeners decide. Mediator: the hub decides. Facade: one-way, the subsystem does not know the facade exists.
- Raise the god-object risk before the interviewer does, and say how you would split the mediator.
Real-world applications
- Dialog and form controllers that enable, disable and fill widgets based on other widgets.
- Radio button groups: Swing's
ButtonGroup, HTML radio inputs that share aname. - Chat rooms and multiplayer game lobbies that route messages between connected users.
- Air traffic control, elevator group controllers and other dispatchers that coordinate many independent units.
- In-process request dispatchers such as .NET's MediatR, and UI controllers and view models in MVC and MVVM.
- At system scale: workflow orchestrators and message brokers between services.
Test yourself
In the visualizer's With Mediator version, the user ticks the box. Who calls addr.setEnabled(false)?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.