Mediator Pattern
A Mediator is one object that a group of peers talk to instead of talking to each other. Each peer holds a single reference – the hub – and the hub holds the membership list and the rules that govern the interaction. The peers lose their references to one another, and with them the ability to make decisions about one another.
💡 Peer mesh = every object holding a direct reference to every other object it talks to. GoF calls the peers Colleagues and the hub the Mediator.
Why this matters: chat rooms, auctions, elevator banks and token-queue systems all turn up in machine-coding rounds, and each is a set of peers that must react to each other. Interviewers watch one thing: whether your peer class holds a collection of other peers. If it does, you will be asked what happens when someone leaves, and the answer – “every other object has to be told” – is the whole conversation.
Prerequisites
- Observer Pattern – a mediator notifies its peers using Observer, so the two are layered rather than alternatives
- Facade Pattern – the closest neighbour, and the difference is direction: callers call into a Facade, which never calls back out
- SOLID Principles – a peer that does its own job and enforces the group’s rules has two responsibilities
The Problem: the chat room where every User holds every other User
The obvious first design gives User a list of the other users and a send that loops over it. It demos fine, and every cost arrives the moment membership changes:
// A chat room with no mediator: every User knows every other User.
public class User {
private final String id;
private final List<User> peers = new ArrayList<>(); // everyone else in the room
private final Set<String> blocked = new HashSet<>();
private final RateLimiter limiter = new RateLimiter(5, Duration.ofSeconds(10));
public void join(List<User> room) {
for (User other : room) {
this.peers.add(other);
other.peers.add(this); // n writes, spread across n different objects
}
}
public void leave() {
for (User other : peers) other.peers.remove(this); // n more, and a miss is fatal
peers.clear();
}
public void send(String text) {
if (!limiter.allow()) return; // a room rule, enforced by the sender,
// and carried by every User in the room
for (User peer : peers) {
if (peer.blocked.contains(this.id)) continue; // another object's policy
if (this.blocked.contains(peer.id)) continue;
peer.receive(this.id, text);
}
}
public void receive(String fromId, String text) {
System.out.println("[" + id + "] " + fromId + ": " + text);
}
}
Three costs, and interviewers name all three:
- Membership is a write to every object in the room.
joinis O(n) writes across n objects, andleaveis O(n) again but worse, because correctness depends on every peer dropping the reference. One missed removal is two bugs: the departedUserstays reachable and is never collected, and it keeps receiving messages from a conversation it left. - Every rule about the conversation lives inside
User, enforced by the sender. Mute, block, rate limit, “only members may post” – each is a field plus a branch inUser, carried by every instance, andpeer.blocked.contains(this.id)reaches into another object to read its policy. A block is a fact about a pair, so neither user is its natural owner, and the rule is only as reliable as the least-correct sender in the room. - A
Usercannot be unit-tested without n otherUsers. Asserting “a rate-limited sender delivers nothing” means building a whole room, because the delivery loop and the policy both sit inside the object you are trying to isolate.
Underneath all three is one number. A fully connected room of n peers holds n(n-1) references – O(n^2), rewritten on every join and leave. That is the number the pattern exists to kill: the hub form holds n references, and a join or a leave is one write to one object.
Class Diagram
classDiagram
class ChatMediator {
<<interface>>
+register(Participant p)
+unregister(String participantId)
+send(String fromId, String text) SendOutcome
}
class ChatRoom {
-Map~String, Participant~ members
-Set~String~ blockedPairs
-Deque~Message~ history
+block(String blockerId, String blockedId)
}
class Participant {
<<interface>>
+id() String
+receive(Message m)
}
class ChatUser {
-ChatMediator room
-String id
+send(String text) SendOutcome
}
class ArchiveBot {
-String id
}
ChatMediator <|.. ChatRoom
Participant <|.. ChatUser
Participant <|.. ArchiveBot
ChatRoom --> Participant
ChatUser --> ChatMediator
The interesting part is the arrows that are missing: no ChatUser --> ChatUser edge exists, and a tenth participant adds exactly one arrow. ChatUser also points at ChatMediator rather than ChatRoom, which is what lets a participant be tested against a fake room, and why ArchiveBot could be written by someone who never read ChatUser.
Real-World Example: Chat Room with Blocking, Rate Limits and Replay
import java.time.*;
import java.util.*;
public record Message(String fromId, String text, Instant at) { }
public enum SendOutcome { DELIVERED, RATE_LIMITED, NOT_A_MEMBER }
// The peer side: an id and an inbox. That is the entire contract.
public interface Participant {
String id();
void receive(Message message);
}
// The hub's contract. A peer never sees anything else.
public interface ChatMediator {
void register(Participant participant);
void unregister(String participantId);
SendOutcome send(String fromId, String text);
}
// The mediator: membership, rules and history in one object.
public final class ChatRoom implements ChatMediator {
private static final int HISTORY_SIZE = 50;
private final Clock clock;
private final RateLimiter limiter; // sliding window, five sends per ten seconds
private final Map<String, Participant> members = new LinkedHashMap<>();
private final Set<String> blockedPairs = new HashSet<>(); // "blocker>blocked"
private final Deque<Message> history = new ArrayDeque<>();
public ChatRoom(Clock clock, RateLimiter limiter) {
this.clock = clock;
this.limiter = limiter;
}
// One write to one object, plus the replay a joiner expects.
@Override public void register(Participant participant) {
members.put(participant.id(), participant);
history.forEach(participant::receive); // last N messages, oldest first
}
// Also one write to one object. No peer has to be told anything.
@Override public void unregister(String participantId) {
members.remove(participantId);
limiter.forget(participantId);
}
@Override public SendOutcome send(String fromId, String text) {
if (!members.containsKey(fromId)) return SendOutcome.NOT_A_MEMBER;
if (!limiter.allow(fromId)) return SendOutcome.RATE_LIMITED;
Message message = new Message(fromId, text, clock.instant());
history.addLast(message);
if (history.size() > HISTORY_SIZE) history.removeFirst();
for (Participant to : List.copyOf(members.values())) { // snapshot: a receive may send
if (to.id().equals(fromId)) continue;
// The rule only the hub can enforce: a block is a fact about the
// *pair*, so neither of the two participants is its natural owner.
if (isBlocked(fromId, to.id())) continue;
try {
to.receive(message);
} catch (RuntimeException e) {
unregister(to.id()); // evict it; one bad peer cannot stop the rest
}
}
return SendOutcome.DELIVERED;
}
// Declared one-directionally, enforced both ways.
public void block(String blockerId, String blockedId) {
blockedPairs.add(blockerId + ">" + blockedId);
}
private boolean isBlocked(String fromId, String toId) {
return blockedPairs.contains(toId + ">" + fromId) // recipient blocked sender
|| blockedPairs.contains(fromId + ">" + toId); // sender blocked recipient
}
}
// The peer: one reference, one id, and a one-line send.
public final class ChatUser implements Participant {
private final String id;
private final ChatMediator room; // the only other object it knows about
public ChatUser(String id, ChatMediator room) { this.id = id; this.room = room; }
@Override public String id() { return id; }
// The entire peer side of the pattern. No loop, no list, no policy.
public SendOutcome send(String text) { return room.send(id, text); }
@Override public void receive(Message m) {
System.out.printf("[%s] %s: %s%n", id, m.fromId(), m.text());
}
}
ChatRoom room = new ChatRoom(Clock.systemUTC(), new SlidingWindowLimiter(5, 10_000));
ChatUser alice = new ChatUser("alice", room);
room.register(alice);
room.register(new ChatUser("bob", room)); // one write; alice is untouched
room.block("bob", "carol"); // bob and carol are mutually silent
alice.send("standup in five"); // fan-out is the hub's problem
room.unregister("bob"); // one write; no peer is told
from collections import defaultdict, deque
from datetime import datetime, timezone
# Message, ChatUser and the sliding-window RateLimiter are as in the Java tab.
# Participant is structural here: anything with an id and a receive qualifies.
class ChatRoom:
"""The mediator. Holds the members, the rules and the history -- nothing else does."""
HISTORY = 50
def __init__(self, limiter: "RateLimiter") -> None:
self._limiter = limiter
# id -> the live sessions for that id. A defaultdict means a second device
# (phone plus laptop, same user) joins with no "first connection" branch.
self._members: defaultdict[str, list["Participant"]] = defaultdict(list)
self._blocked: set[tuple[str, str]] = set() # (blocker, blocked)
self._history: deque["Message"] = deque(maxlen=self.HISTORY)
def register(self, participant: "Participant") -> None:
self._members[participant.id].append(participant)
for past in self._history: # last N replayed on join
participant.receive(past)
def unregister(self, participant: "Participant") -> None:
sessions = self._members.get(participant.id, [])
if participant in sessions:
sessions.remove(participant)
if not sessions: # last device gone
self._members.pop(participant.id, None)
self._limiter.forget(participant.id)
def block(self, blocker_id: str, blocked_id: str) -> None:
self._blocked.add((blocker_id, blocked_id))
def send(self, from_id: str, text: str) -> str:
if from_id not in self._members:
return "NOT_A_MEMBER"
if not self._limiter.allow(from_id):
return "RATE_LIMITED"
message = Message(from_id, text, datetime.now(timezone.utc))
self._history.append(message)
for peer_id, sessions in list(self._members.items()): # snapshot: receive may send
if peer_id == from_id or self._is_blocked(from_id, peer_id):
continue
for session in list(sessions):
session.receive(message)
return "DELIVERED"
def _is_blocked(self, a: str, b: str) -> bool:
# Both ways, because the hub is the only object that sees the pair.
return (a, b) in self._blocked or (b, a) in self._blocked
#include <chrono>
#include <memory>
#include <string>
#include <vector>
// Message, Participant, the blocked-pair check, the limiter and the replay history
// are as in the Java tab. This tab is about what C++ forces you to decide: lifetime.
// The hub holds weak_ptr, never shared_ptr. Participant lifetime belongs to
// whoever owns the session -- the connection handler, the test, main(). A room
// must not be the reason a departed participant is still alive: with shared_ptr
// here, one forgotten unregister pins the object for as long as the room lives,
// which is the mesh's leak, merely centralised.
class ChatRoom {
struct Member {
std::string id;
std::weak_ptr<Participant> handle;
};
std::vector<Member> members_;
public:
void registerParticipant(const std::shared_ptr<Participant>& p) {
members_.push_back(Member{p->id(), p}); // shared_ptr decays to weak
}
void unregister(const std::string& id) {
std::erase_if(members_, [&](const Member& m) { return m.id == id; });
}
void send(const std::string& fromId, const std::string& text) {
const Message message{fromId, text, std::chrono::system_clock::now()};
// An expired handle is a participant destroyed without unregistering, so
// one pass reaps it. A missed unregister is self-correcting here; in the
// mesh the stale reference sat inside every peer, and nothing swept it.
std::erase_if(members_, [](const Member& m) { return m.handle.expired(); });
// Deliver over a copy: a participant may register or send from inside
// receive, which would invalidate iterators into members_.
const std::vector<Member> snapshot = members_;
for (const Member& m : snapshot) {
const std::shared_ptr<Participant> peer = m.handle.lock();
if (!peer || m.id == fromId) continue;
peer->receive(message);
}
}
};
The hub owns the rules, not just the routing
A mediator that only forwards is a message bus: one indirection and a class to maintain. If ChatRoom.send were members.values().forEach(p -> p.receive(m)) and nothing else, the honest review comment is “this is a list with extra steps.”
A mediator earns its place when it holds policy about the relationship between peers: who may talk to whom, in what order, under what limit. Above, three such rules no participant could own:
isBlocked(from, to)– a predicate over a pair. Neither user is its natural owner, and putting it in the sender means trusting the sender.- The rate limit – a quota across one peer’s interactions with the group, which a peer could track but could also simply not.
- The history and the replay – a property of the conversation, not of anyone in it. A joiner’s first 50 messages come from the room, which is what persisted.
GoF’s original motivating case is a dialog box, and interviewers still use it. Submit should enable only when three fields are valid. Without a mediator the email field needs references to the password field and the terms checkbox to decide; with one, each widget reports “I changed” and the dialog – GoF calls it the director – reads all three and decides what to enable. The widgets stay dumb and reusable. Same tell as the chat case: the rule spans more than one peer, so it lives in the only object that can see more than one.
A mediator does not remove complexity, it relocates it into one class that imports every peer type. That class grows, and left alone becomes a god object. The mitigation is worth memorising: one mediator per interaction, not one per application. A ChatRoom per room is a mediator; a ChatService holding every room and every rule in the product is a god object wearing the pattern’s name.
Mediator vs Observer vs Facade vs Event Bus
All four sit “in the middle” of several objects. The separating questions: how many parties talk in each direction, and whether the middle knows who they are:
| Pattern | Intent | Tell |
|---|---|---|
| Mediator | Replace an N-to-N peer mesh with one hub owning the interaction rules | Many-to-many; the hub knows every peer by identity and the rules between peers live in it |
| Observer | Notify many dependents when one subject changes state | One-to-many; the publisher does not know who subscribed and holds no rule about them |
| Facade | Give callers one small API over a subsystem you own | One-directional – callers call in, the subsystem never calls back out |
| Event Bus / Pub-Sub | Decouple producers from consumers through named topics | A Mediator with peer identities erased, so no rule can name two peers |
Mediator and Observer are usually combined, not chosen between, and saying so is the fastest way to show you have built one: the mediator is the subject, peers register with it, and send is a notify with a policy filter in front. Chat Application is exactly that – ChatRoom the mediator, Participant the observer interface, isBlocked the filter.
The Event Bus row is the trade you make at scale, and it cuts both ways: erasing peer identity is what lets a broker serve a million topics it has never heard of, and it is also why you can no longer write isBlocked(from, to) – the bus does not know who to is. Hence Pub Sub System has topics and filters but no concept of two subscribers having a relationship.
When to Use vs When to Avoid
| Use Mediator When | Avoid When |
|---|---|
| Peers would hold references to each other and the count grows with membership | There are two peers and always will be – a direct reference is clearer |
| A rule is about a pair or a group: who may talk to whom, in what order, under what quota | The hub would only forward, adding no rule – use an event bus |
| Membership churns, so a join or leave must be one write rather than n | One-to-many broadcast with no rules between listeners – use Observer |
| Several dumb components must coordinate, like a form where Submit needs three fields | Callers only call in and the subsystem never calls back – a Facade |
| The interaction has a lifecycle worth an object: a room, a game, a call, a queue | Peers must stay usable standalone, outside any hub |
The characteristic failure mode is the god mediator, with three symptoms. It imports every peer type in the program. It has a method per peer rather than per interaction – onLoginButtonClicked, onPasswordFieldChanged, onCaptchaRefreshed – which is the real giveaway, because a method per peer means the hub absorbed each peer’s own logic rather than the logic between them. And every feature adds a branch, so the class meant to decouple everything becomes the file every change touches.
The split rule: cut the mediator wherever two groups of peers never appear in the same rule. If no policy mentions a chat participant and a billing record together, those are two mediators, however convenient one class would be. And when the hub’s logic turns out to be a lifecycle rather than a set of rules – room created, open, archived – the right move is not another if but a state machine inside the mediator, with a transition table replacing the branches.
Interview Questions
-
“Mediator vs Observer – what is the actual difference?” – Direction and knowledge. Observer is one-to-many: the subject fires an event, does not know who subscribed, and structurally cannot hold a rule involving two particular subscribers. Mediator is many-to-many: the hub knows every peer by id, which is what lets
sendask “may alice’s message reach bob”. You normally implement one with the other, so the useful question is not “which pattern” but “where does a rule between two peers live” – and only Mediator answers it. -
“Should the mediator be a singleton?” – No, and yes is the most common wrong answer in the room. One mediator per interaction: a
ChatRoomper room, aGameper game, aCallSessionper call. A singleton forces the room id into every signature and turns every rule into a lookup, but the real cost is the scaling story – one object per room means rooms are independently lockable today and independently placeable on separate servers tomorrow, where a global mediator is one lock for every conversation in the product. If callers must find a room by id, that is a registry handing out instances, not a singleton mediator. -
“How does this map onto a real distributed chat system?” – The mediator becomes a server-side room actor: still one object per room, still owning the member list, the block list and the history. The fan-out is what changes –
to.receive(message)becomes a push over WebSockets to each connected session, plus a publish to a message broker for sessions on other servers. The in-process pattern is the same shape; the network adds that delivery can fail silently and the history must be durable, because replay-on-join becomes how a reconnecting client catches up. -
“How do you keep the mediator from becoming a bottleneck under concurrency?” – One lock per room, never one global lock. The hub is already one object per interaction, so guarding its membership map and history with that room’s own lock means two rooms never contend. Then get the fan-out out from under the lock: snapshot the member list, or hold it in a copy-on-write list, so a slow
receivecannot block a join. Concurrency names the trade-off – a participant joining mid-fan-out misses the in-flight message, which is right for chat and wrong for an order book. -
“What happens when a peer’s
receivethrows, or blocks?” – The hub is the only object that can answer, which is an argument for the pattern rather than against it. Inline delivery means one broken participant stops delivery for everyone later in the iteration order, so catch per recipient, keep going, and evict a peer that keeps throwing. Blocking is harder: ifreceivecan block on a socket write, the hub must hand off to a per-participant queue, and at that point the mediator has grown into message queues with the room as the routing rule.
See It in Action
- Chat Application –
ChatRoomis the mediator and notifiesParticipants using Observer, with blocking in the hub - Queue Management – tokens and counters never reference each other; the queue manager owns assignment
- Elevator System – the controller mediates between floor buttons, cars and the dispatch policy
- Pub Sub System – a mediator with subscriber identity erased, so no rule can name two peers