Mediator Pattern
Put five objects in a room and let each one talk to every other one directly, and you have up to twenty one-way relationships to maintain. Add a sixth and it's thirty. Worse than the number is where the rules live: "when the checkbox is ticked, enable the company field, and enable the submit button only if the email is valid and the company field is filled" ends up split across the checkbox, the field and the button, each reaching into the others. Mediator takes those rules out of the participants and puts them in one place that everybody talks to instead.
The grouped behavioral patterns overview mentions Mediator only in passing. This page covers it properly: the structure, a chat room in Java, Python and TypeScript, air traffic control as an example of protecting a shared resource, UI dialogs (the pattern's original home), how it differs from Observer, and the main way it goes wrong.
Intent
Define an object that encapsulates how a set of objects interact. The objects no longer refer to each other directly. They talk only to the mediator, which decides who needs to know what and enforces the rules of the interaction.
The participants are usually called colleagues. The trade is simple: many-to-many links between colleagues become one-to-many links between the mediator and its colleagues. The colleagues get simpler and reusable, because they no longer know about each other. The mediator gets the coordination logic, and with it the risk of growing too big.
flowchart LR
subgraph before["Before: every colleague knows the others"]
A1["Checkbox"] <--> B1["Company field"]
A1 <--> C1["Submit button"]
B1 <--> C1
D1["Email field"] <--> C1
D1 <--> B1
end
subgraph after["After: colleagues know only the mediator"]
M["SignupDialog (mediator)"]
A2["Checkbox"] <--> M
B2["Company field"] <--> M
C2["Submit button"] <--> M
D2["Email field"] <--> M
end
The problem
Here's a signup form written the direct way. Each widget holds references to the widgets it affects and updates them when it changes:
final class TextField {
String text = "";
boolean enabled = true;
SubmitButton submit; // the field knows about the button...
void type(String value) {
text = value;
submit.refresh(); // ...and pokes it on every change
}
}
final class CompanyCheckbox {
boolean checked;
TextField companyField; // the checkbox knows about the company field...
SubmitButton submit; // ...and the button
void toggle() {
checked = !checked;
companyField.enabled = checked;
if (!checked) companyField.text = "";
submit.refresh();
}
}
final class SubmitButton {
boolean enabled;
TextField email; // the button knows about everyone
TextField companyField;
CompanyCheckbox isCompany;
void refresh() {
boolean emailOk = email.text.contains("@");
boolean companyOk = !isCompany.checked || !companyField.text.isBlank();
enabled = emailOk && companyOk;
}
}
class BeforeDemo {
public static void main(String[] args) {
TextField email = new TextField();
TextField company = new TextField();
CompanyCheckbox box = new CompanyCheckbox();
SubmitButton submit = new SubmitButton();
// Wiring: every object needs references to the others, in the right order.
email.submit = submit;
company.submit = submit;
company.enabled = false;
box.companyField = company;
box.submit = submit;
submit.email = email;
submit.companyField = company;
submit.isCompany = box;
email.type("asha@example.com");
assert submit.enabled;
box.toggle();
assert company.enabled && !submit.enabled;
company.type("Acme");
assert submit.enabled;
System.out.println("before: ok");
}
}
Each class is small, so what's the problem?
- The rules are scattered. "Submit is enabled when..." lives in
SubmitButton. "Unticking clears the company field" lives inCompanyCheckbox. To understand the form's behaviour you read every class. - The widgets can't be reused.
TextFieldhas aSubmitButtonfield. You can't drop it into a search bar that has no submit button without editing it.CompanyCheckboxonly works next to a company field. - The wiring is fragile. Eight assignments in a particular order, and forgetting one gives a
NullPointerExceptionthe first time someone types. - Every new rule touches several classes. Add a "VAT number required for EU companies" rule and you edit the checkbox, a new country picker, the company field and the button, and add references between them all.
- The number of links grows fast. With n colleagues that all know each other there are up to n(n−1) directed references. Every new widget potentially links to every existing one.
Structure
classDiagram
class ChatMediator {
<<interface>>
+join(member: Member) void
+broadcast(from: Member, text: String) void
+direct(from: Member, to: String, text: String) void
}
class ChatRoom {
-members: Map~String, Member~
-muted: Set~String~
-history: List~String~
+join(member: Member) void
+broadcast(from: Member, text: String) void
+direct(from: Member, to: String, text: String) void
+mute(name: String) void
}
class Member {
-name: String
-room: ChatMediator
-inbox: List~String~
+say(text: String) void
+whisper(to: String, text: String) void
+receive(line: String) void
}
ChatMediator <|.. ChatRoom
Member --> ChatMediator : talks only to
ChatRoom o-- Member : coordinates
The arrows are the point. Member has no reference to any other Member. It knows the mediator interface, and the mediator knows every member.
Participants
| Participant | Role in the example | Responsibility |
|---|---|---|
| Mediator | ChatMediator | The interface colleagues use to report events or make requests. Optional: if there's only ever one mediator, the concrete class is enough. It earns its keep when you want to test a colleague against a fake mediator. |
| Concrete mediator | ChatRoom | Knows all colleagues and holds the coordination rules: who receives a broadcast, what muting means, whether a direct message's recipient exists, what gets recorded in history. |
| Colleague | Member | Does its own job (here, holding an inbox) and tells the mediator about anything other colleagues might care about. Never calls another colleague directly. |
Colleagues talk to the mediator in one of two styles. Either they call specific methods (room.broadcast(this, text)), as here, or they send a generic notification (dialog.changed(this)) and the mediator works out what changed. The first is clearer and type-checked. The second keeps colleagues completely generic, which suits UI widgets you want to reuse anywhere; the dialog example below uses it.
Implementation
The chat room is the standard teaching example for a reason: the rules are easy to state and they genuinely belong to the room, not to any member. Members can join, say something to everyone, or whisper to one person. The room refuses duplicate names, doesn't echo a message back to its sender, blocks muted members and tells the sender when a whisper's recipient doesn't exist.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
interface ChatMediator {
void join(Member member);
void broadcast(Member from, String text);
void direct(Member from, String to, String text);
}
final class Member {
private final String name;
private final List<String> inbox = new ArrayList<>();
private ChatMediator room;
Member(String name) { this.name = name; }
String name() { return name; }
void joined(ChatMediator room) { this.room = room; }
void say(String text) { room().broadcast(this, text); }
void whisper(String to, String text) { room().direct(this, to, text); }
void receive(String line) { inbox.add(line); }
List<String> inbox() { return List.copyOf(inbox); }
private ChatMediator room() {
if (room == null) throw new IllegalStateException(name + " has not joined a room");
return room;
}
}
final class ChatRoom implements ChatMediator {
private final Map<String, Member> members = new LinkedHashMap<>();
private final Set<String> muted = new HashSet<>();
private final List<String> history = new ArrayList<>();
@Override
public void join(Member member) {
if (members.putIfAbsent(member.name(), member) != null) {
throw new IllegalArgumentException("name already taken: " + member.name());
}
member.joined(this);
for (Member m : members.values()) m.receive("[room] " + member.name() + " joined");
}
@Override
public void broadcast(Member from, String text) {
if (muted.contains(from.name())) {
from.receive("[room] you are muted");
return;
}
String line = from.name() + ": " + text;
history.add(line);
for (Member m : members.values()) {
if (m != from) m.receive(line); // no echo to the sender
}
}
@Override
public void direct(Member from, String to, String text) {
Member target = members.get(to);
if (target == null) {
from.receive("[room] no member called " + to);
return;
}
target.receive("(whisper) " + from.name() + ": " + text);
}
void mute(String name) { muted.add(name); }
List<String> history() { return List.copyOf(history); }
}
class ChatDemo {
public static void main(String[] args) {
ChatRoom room = new ChatRoom();
Member asha = new Member("asha");
Member ravi = new Member("ravi");
Member li = new Member("li");
room.join(asha);
room.join(ravi);
room.join(li);
asha.say("standup in 5");
assert ravi.inbox().contains("asha: standup in 5");
assert !asha.inbox().contains("asha: standup in 5");
ravi.whisper("li", "coffee after?");
assert li.inbox().contains("(whisper) ravi: coffee after?");
assert !asha.inbox().contains("(whisper) ravi: coffee after?");
ravi.whisper("sam", "hello?");
assert ravi.inbox().contains("[room] no member called sam");
room.mute("li");
li.say("spam spam spam");
assert li.inbox().contains("[room] you are muted");
assert room.history().equals(List.of("asha: standup in 5"));
try { room.join(new Member("asha")); assert false; } catch (IllegalArgumentException expected) { }
System.out.println("chat room: ok");
}
}
from __future__ import annotations
from typing import Protocol
class ChatMediator(Protocol):
def join(self, member: Member) -> None: ...
def broadcast(self, sender: Member, text: str) -> None: ...
def direct(self, sender: Member, to: str, text: str) -> None: ...
class Member:
def __init__(self, name: str) -> None:
self.name = name
self.inbox: list[str] = []
self._room: ChatMediator | None = None
def joined(self, room: ChatMediator) -> None:
self._room = room
def say(self, text: str) -> None:
self._require_room().broadcast(self, text)
def whisper(self, to: str, text: str) -> None:
self._require_room().direct(self, to, text)
def receive(self, line: str) -> None:
self.inbox.append(line)
def _require_room(self) -> ChatMediator:
if self._room is None:
raise RuntimeError(f"{self.name} has not joined a room")
return self._room
class ChatRoom:
def __init__(self) -> None:
self._members: dict[str, Member] = {}
self._muted: set[str] = set()
self.history: list[str] = []
def join(self, member: Member) -> None:
if member.name in self._members:
raise ValueError(f"name already taken: {member.name}")
self._members[member.name] = member
member.joined(self)
for m in self._members.values():
m.receive(f"[room] {member.name} joined")
def broadcast(self, sender: Member, text: str) -> None:
if sender.name in self._muted:
sender.receive("[room] you are muted")
return
line = f"{sender.name}: {text}"
self.history.append(line)
for m in self._members.values():
if m is not sender: # no echo to the sender
m.receive(line)
def direct(self, sender: Member, to: str, text: str) -> None:
target = self._members.get(to)
if target is None:
sender.receive(f"[room] no member called {to}")
return
target.receive(f"(whisper) {sender.name}: {text}")
def mute(self, name: str) -> None:
self._muted.add(name)
if __name__ == "__main__":
room = ChatRoom()
asha, ravi, li = Member("asha"), Member("ravi"), Member("li")
for m in (asha, ravi, li):
room.join(m)
asha.say("standup in 5")
assert "asha: standup in 5" in ravi.inbox
assert "asha: standup in 5" not in asha.inbox
ravi.whisper("li", "coffee after?")
assert "(whisper) ravi: coffee after?" in li.inbox
assert "(whisper) ravi: coffee after?" not in asha.inbox
ravi.whisper("sam", "hello?")
assert "[room] no member called sam" in ravi.inbox
room.mute("li")
li.say("spam spam spam")
assert "[room] you are muted" in li.inbox
assert room.history == ["asha: standup in 5"]
try:
room.join(Member("asha"))
raise AssertionError("duplicate name accepted")
except ValueError:
pass
print("chat room: ok")
interface ChatMediator {
join(member: Member): void;
broadcast(from: Member, text: string): void;
direct(from: Member, to: string, text: string): void;
}
class Member {
private room: ChatMediator | null = null;
private readonly lines: string[] = [];
constructor(readonly name: string) {}
joined(room: ChatMediator): void {
this.room = room;
}
say(text: string): void {
this.requireRoom().broadcast(this, text);
}
whisper(to: string, text: string): void {
this.requireRoom().direct(this, to, text);
}
receive(line: string): void {
this.lines.push(line);
}
get inbox(): readonly string[] {
return [...this.lines];
}
private requireRoom(): ChatMediator {
if (this.room === null) throw new Error(`${this.name} has not joined a room`);
return this.room;
}
}
class ChatRoom implements ChatMediator {
private readonly members = new Map<string, Member>();
private readonly muted = new Set<string>();
private readonly log: string[] = [];
join(member: Member): void {
if (this.members.has(member.name)) throw new Error(`name already taken: ${member.name}`);
this.members.set(member.name, member);
member.joined(this);
for (const m of this.members.values()) m.receive(`[room] ${member.name} joined`);
}
broadcast(from: Member, text: string): void {
if (this.muted.has(from.name)) {
from.receive("[room] you are muted");
return;
}
const line = `${from.name}: ${text}`;
this.log.push(line);
for (const m of this.members.values()) {
if (m !== from) m.receive(line); // no echo to the sender
}
}
direct(from: Member, to: string, text: string): void {
const target = this.members.get(to);
if (target === undefined) {
from.receive(`[room] no member called ${to}`);
return;
}
target.receive(`(whisper) ${from.name}: ${text}`);
}
mute(name: string): void {
this.muted.add(name);
}
get history(): readonly string[] {
return [...this.log];
}
}
function check(condition: boolean, message: string): void {
if (!condition) throw new Error(`check failed: ${message}`);
}
const room = new ChatRoom();
const asha = new Member("asha");
const ravi = new Member("ravi");
const li = new Member("li");
[asha, ravi, li].forEach((m) => room.join(m));
asha.say("standup in 5");
check(ravi.inbox.includes("asha: standup in 5"), "broadcast reaches others");
check(!asha.inbox.includes("asha: standup in 5"), "no echo");
ravi.whisper("li", "coffee after?");
check(li.inbox.includes("(whisper) ravi: coffee after?"), "whisper reaches target");
check(!asha.inbox.includes("(whisper) ravi: coffee after?"), "whisper is private");
ravi.whisper("sam", "hello?");
check(ravi.inbox.includes("[room] no member called sam"), "unknown recipient reported");
room.mute("li");
li.say("spam spam spam");
check(li.inbox.includes("[room] you are muted"), "muted member is told");
check(room.history.length === 1 && room.history[0] === "asha: standup in 5", "muted message not recorded");
let duplicateRejected = false;
try {
room.join(new Member("asha"));
} catch {
duplicateRejected = true;
}
check(duplicateRejected, "duplicate name rejected");
console.log("chat room: ok");
What to notice:
- Every rule lives in
ChatRoom. Muting, no-echo, history and the unknown-recipient reply are all room policy. To add "slow mode: one message per member every 10 seconds", you changeChatRoomand nothing else.Membernever learns that muting exists. Memberis reusable. The same class works in a different mediator (a two-person private chat, a moderated room that holds messages for approval) because it depends only on theChatMediatorinterface.- Feedback goes through the mediator too. When a whisper fails, the room tells the sender. The sender doesn't query the room's membership list and decide for itself, which would leak the room's rules back into the colleague.
- Concurrency is the mediator's job. In a real server, messages arrive on many threads at once. Because every interaction passes through the room, one lock (or one event loop, or one actor) in the room gives you a consistent ordering of messages and membership changes. That's a genuine advantage of centralising: there's exactly one place to make thread-safe. The examples here are single-threaded to keep them short.
Air traffic control
Air traffic control is the classic real-world analogy, and it's useful in an interview because it shows a different side of the pattern: the mediator protects a shared resource. Aircraft never negotiate with each other about who lands next. Each one talks to the tower, and the tower enforces the rule that only one aircraft uses the runway at a time.
from __future__ import annotations
from collections import deque
class Aircraft:
def __init__(self, callsign: str, tower: ControlTower) -> None:
self.callsign = callsign
self.tower = tower
self.messages: list[str] = []
def request_landing(self) -> None:
self.tower.request_landing(self)
def landed_and_cleared_runway(self) -> None:
self.tower.runway_vacated(self)
def notify(self, message: str) -> None:
self.messages.append(message)
class ControlTower:
"""The mediator: aircraft never talk to each other, and the runway is never double-booked."""
def __init__(self) -> None:
self._on_runway: Aircraft | None = None
self._holding: deque[Aircraft] = deque()
def request_landing(self, plane: Aircraft) -> None:
if plane is self._on_runway or plane in self._holding:
plane.notify("already in sequence")
return
if self._on_runway is None:
self._clear(plane)
else:
self._holding.append(plane)
plane.notify(f"hold, number {len(self._holding)} in sequence")
def runway_vacated(self, plane: Aircraft) -> None:
if plane is not self._on_runway:
raise ValueError(f"{plane.callsign} was not cleared to use the runway")
self._on_runway = None
if self._holding:
self._clear(self._holding.popleft())
def _clear(self, plane: Aircraft) -> None:
self._on_runway = plane
plane.notify("cleared to land")
if __name__ == "__main__":
tower = ControlTower()
ai101 = Aircraft("AI101", tower)
ba202 = Aircraft("BA202", tower)
lh303 = Aircraft("LH303", tower)
ai101.request_landing()
ba202.request_landing()
lh303.request_landing()
assert ai101.messages == ["cleared to land"]
assert ba202.messages == ["hold, number 1 in sequence"]
assert lh303.messages == ["hold, number 2 in sequence"]
ai101.landed_and_cleared_runway()
assert ba202.messages[-1] == "cleared to land"
assert lh303.messages == ["hold, number 2 in sequence"]
try:
lh303.landed_and_cleared_runway() # it was never cleared
raise AssertionError("tower accepted a vacate from a holding aircraft")
except ValueError:
pass
print("control tower: ok")
Imagine the alternative: each aircraft keeps a list of other aircraft, broadcasts "I'm landing" and waits for objections. Every aircraft would need the same conflict-resolution logic, they would all have to agree on ordering, and two that broadcast at the same moment would both think they'd won. That's a distributed consensus problem. The tower turns it into a queue. In code, the same idea applies to anything that allocates a scarce resource among peers: a meeting-room booker, a parking lot's spot allocator, an elevator dispatcher choosing which car answers a call (see the elevator system case study).
UI dialogs
Dialogs and forms are where the pattern was first described, and they're still its most natural fit. Widgets such as text fields, checkboxes and buttons should be generic and reusable. The rules about how they affect each other are specific to one dialog. So the widgets report "I changed" to the dialog, and the dialog applies its rules. Here is the signup form from the problem section, rebuilt:
interface DialogMediator {
changed(widget: Widget): void;
}
abstract class Widget {
enabled = true;
constructor(readonly id: string, protected readonly dialog: DialogMediator) {}
protected notify(): void {
this.dialog.changed(this);
}
}
class TextField extends Widget {
text = "";
type(value: string): void {
if (!this.enabled) return;
this.text = value;
this.notify();
}
clear(): void {
this.text = ""; // set directly: clearing is the dialog's decision, so no notify loop
}
}
class Checkbox extends Widget {
checked = false;
toggle(): void {
this.checked = !this.checked;
this.notify();
}
}
class Button extends Widget {}
/** The mediator: every cross-widget rule lives here and nowhere else. */
class SignupDialog implements DialogMediator {
readonly email = new TextField("email", this);
readonly isCompany = new Checkbox("isCompany", this);
readonly company = new TextField("company", this);
readonly submit = new Button("submit", this);
constructor() {
this.refresh();
}
changed(widget: Widget): void {
if (widget === this.isCompany && !this.isCompany.checked) this.company.clear();
this.refresh();
}
private refresh(): void {
this.company.enabled = this.isCompany.checked;
const emailOk = /^[^@\s]+@[^@\s]+$/.test(this.email.text);
const companyOk = !this.isCompany.checked || this.company.text.trim() !== "";
this.submit.enabled = emailOk && companyOk;
}
}
function check(condition: boolean, message: string): void {
if (!condition) throw new Error(`check failed: ${message}`);
}
const dialog = new SignupDialog();
check(!dialog.submit.enabled && !dialog.company.enabled, "initial state");
dialog.email.type("asha@example.com");
check(dialog.submit.enabled, "valid email enables submit");
dialog.isCompany.toggle();
check(dialog.company.enabled && !dialog.submit.enabled, "company account needs a name");
dialog.company.type("Acme");
check(dialog.submit.enabled, "name supplied");
dialog.isCompany.toggle();
check(!dialog.company.enabled && dialog.company.text === "" && dialog.submit.enabled, "unticking clears");
dialog.company.type("ignored");
check(dialog.company.text === "", "disabled field ignores typing");
console.log("signup dialog: ok");
Compare it with the "before" version. TextField, Checkbox and Button no longer reference each other, so each can appear in any dialog. The rules ("company accounts need a name", "unticking clears the name") are four lines in one method you can read top to bottom. The wiring problem is gone, because the dialog creates its own widgets.
Two practical points:
- Recompute, don't patch.
refresh()derives every widget's state from scratch on each change instead of applying a delta ("the checkbox was ticked, so enable the company field"). For a dialog with a handful of widgets this is cheap, and it removes a whole category of bugs where the state depends on the order of past events. It's the same idea behind React's "UI is a function of state". - Avoid notification loops. If the mediator changes a widget, and that widget notifies the mediator, which changes it again, you recurse forever. Here
clear()sets the text without notifying. The general rule: user-driven changes notify; mediator-driven changes don't.
Mediator vs Observer
These two get confused because both decouple a sender from its receivers, and because mediators are often implemented with observer-style notifications (the widgets above call changed(this), which looks like an event). The difference is in who holds the logic and which way the knowledge points.
| Observer | Mediator | |
|---|---|---|
| Shape | One subject, many observers (one-to-many) | Many colleagues, one hub (many-to-many routed through one) |
| Who knows whom | The subject knows only an abstract list of listeners. Observers know the subject. | The mediator knows every colleague concretely. Colleagues know only the mediator. |
| Where the rules live | In each observer: each one decides how to react | In the mediator: it decides who reacts and how |
| Direction | Typically one-way: subject to observers | Two-way: colleagues report to the mediator, and the mediator commands colleagues |
| Adding a participant | Subscribe a new observer; the subject doesn't change | Usually edit the mediator, which must learn the new colleague's role |
| Typical use | "Tell anyone interested that the order shipped" | "Make these widgets/members/aircraft behave consistently together" |
A quick test: if you delete the central object, what's lost? Delete an observer's subject and you lose a source of events; the reactions are still written in the observers. Delete a mediator and you lose the rules of the interaction, because they were written in the mediator.
An event bus sits between the two. It's a central hub (like a mediator) but it contains no policy (like an observer's subject): it routes events by type to whoever subscribed. That makes it a "dumb" mediator. It's great for decoupling, but it doesn't give you one place to read the rules, because the rules are back in the subscribers. If the requirement is "these components must coordinate according to these rules", you want a real mediator. If it's "these components want to hear about these events", Observer or a bus is enough. The event bus patterns page covers buses in depth.
Keeping the mediator from becoming a god object
The pattern's main risk is built into its definition: it moves complexity from the colleagues into the mediator. Left alone, the mediator becomes the class every change touches, with every rule for every interaction in one file. That's the god class mistake by another route.
Ways to keep it in check:
- One mediator per interaction, not per application. A
SignupDialogmediator and aCheckoutDialogmediator, not aUiMediatorfor every screen. AChatRoomper room, not aChatServerthat holds every room's rules. - Push behaviour that belongs to one colleague back into it. Validating an email is the email field's job (or a validator's). The mediator should only hold rules that involve more than one colleague: "submit depends on email and company".
- Keep the mediator about coordination, not computation. If the tower starts computing glide paths and fuel burn, those belong in other classes that the tower calls.
- Watch the method count and the reasons to change. If the mediator changes for unrelated reasons (moderation rules, message formatting, persistence), split those concerns out into collaborators that the mediator uses.
Real-world uses
- Chat servers. In IRC, Slack, Discord and similar systems, clients don't connect to each other. Each client talks to a server, which decides who receives each message based on channel membership, permissions and moderation. That's the chat room above at scale.
- Air traffic control. The original analogy, and an accurate one: pilots in controlled airspace coordinate through controllers, not with each other.
- Swing's
ButtonGroup. Ajavax.swing.ButtonGroupmakes a set of toggle buttons mutually exclusive: selecting one deselects the others. The buttons don't reference each other; the group coordinates them. - React "lifting state up". When two sibling components must stay in sync, the React documentation recommends moving the shared state into their closest common parent, which passes values and callbacks down. The parent becomes the mediator: siblings never talk to each other directly.
- Command and request dispatchers. .NET's MediatR library (named after the pattern) sends each request object to its handler, so controllers depend on the dispatcher rather than on handler classes. The use cases page shows the same idea in TypeScript. Strictly this is closer to a request router than to the classic colleague-coordinating mediator, but it's where many developers meet the name.
When NOT to use it
- Two or three objects with one simple interaction. A direct call is clearer than a mediator. The pattern pays off when interactions are many-to-many and the rules change.
- The participants don't actually need to coordinate. If one object just announces events and others react independently, that's Observer. Adding a mediator would centralise logic that's better left with each reactor.
- The interaction is a fixed sequence. "Validate, then save, then email" is a workflow, not a coordination problem. A plain service method or a Chain of Responsibility expresses it better.
- The mediator would just forward calls. If every mediator method is
colleagueB.doThing(), you've added a layer without moving any rules into it. The mediator must own some decision to be worth having. - You're crossing process boundaries. Across services, a central coordinator becomes a single point of failure and a deployment bottleneck. Choreography with events, or an orchestrator with durability and retries, are the distributed analogues. See event choreography and event orchestration.
Related patterns
| Pattern | How it differs |
|---|---|
| Observer | One-to-many notification with the reaction logic in each observer. Mediator is many-to-many with the logic in the hub. Mediators often use observer-style notifications internally. |
| Facade | Also a single object in front of many. But a facade simplifies a subsystem for outside callers, and the subsystem classes don't know it exists. A mediator coordinates peers, who do know it and talk to it. |
| Chain of Responsibility | A chain routes a request through handlers that each know only their successor. A mediator routes centrally and knows everyone. |
| Command | Colleagues often send commands to the mediator, and request dispatchers like MediatR route command objects to handlers. |
| State | A mediator coordinating many widgets often has modes ("editing", "submitting"). Modelling those modes as states keeps the mediator's ifs under control. |
The smell that suggests it
- Objects that hold references to many siblings just to keep them in step: the checkbox that knows the field and the button, the button that knows everyone.
- A rule that can't be read in one place: "when can the user submit?" requires reading three classes.
- Reusable-looking components that can't be reused because they reference specific neighbours.
- Long wiring code that assigns cross-references between objects in a careful order, with
NullPointerExceptions when one is missed. - Peers negotiating over a shared resource, such as a runway, a meeting room, a parking spot or a seat, with the conflict logic copied into each peer.
Interview questions
- "What's the difference between Mediator and Observer?" Observer is one-to-many: a subject notifies listeners, and each listener contains its own reaction. Mediator is many-to-many through a hub that contains the coordination rules and actively tells colleagues what to do. A good test is to ask where you'd go to read the rules: in the observers, or in the mediator.
- "Isn't a mediator just a god object?" It can become one, and that's the pattern's main cost. Keep one mediator per interaction (a dialog, a room), keep single-colleague logic in the colleague, and only put rules that involve several colleagues in the mediator.
- "Mediator vs Facade?" Both are one object in front of several. A facade gives outside clients a simpler API to a subsystem, and the subsystem doesn't know about it. A mediator sits between peers who know about it and talk through it. The direction of knowledge is the giveaway.
- "How would you make the chat room thread-safe?" Because every interaction passes through the room, it's the one place to synchronise. A single lock around
join,broadcastanddirectgives a consistent message order. For more throughput, run each room on its own single-threaded executor or actor, so different rooms proceed in parallel while each room stays sequential. Deliver to members outside the lock if delivery can be slow. - "Do colleagues need an interface for the mediator?" Only if there's a reason: more than one mediator implementation, or wanting to unit-test a colleague with a fake mediator. Otherwise the concrete class is fine. Don't add an interface with one implementation just because the diagram has one.
- "How do you test a mediator?" Construct it with real, simple colleagues (or recording fakes) and drive scenarios: the dialog tests above tick the box, type a name and assert on the button. Because all the rules are in one class, the tests concentrate there too, which is a nice side effect of the pattern.
- "Where would you use Mediator in an LLD round?" Look for peers competing for a shared resource or needing to stay consistent: the elevator dispatcher choosing a car for a hall call, a parking lot allocating spots across entry gates, a meeting-room scheduler, an auction house routing bids to watchers, a multiplayer game's server-side room. Say why: it centralises the conflict rules and gives one place to lock.
- "How do you avoid infinite notification loops in a UI mediator?" Distinguish user-driven changes, which notify the mediator, from mediator-driven changes, which don't. Alternatively, have the mediator recompute all derived state from scratch on each notification and ignore notifications that arrive while it's already updating.
Further reading
- Behavioral Patterns overview: the grouped page
- Observer: the pattern Mediator is most often confused with
- Event bus patterns: in-process buses as policy-free mediators
- Pattern Selection Guide: Observer vs Mediator vs Pub-Sub side by side