SyntaxPilot
Courses/Low-Level Design/Lesson 41
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 41 of 90

Mediator pattern

Mediator patternmediatorcolleaguesreducing many-to-many dependencieschat room exampleair-traffic control examplemediator vs observergod-mediator risk

These are the notes for Low-Level Design (LLD) episode 41, the eighth behavioural pattern (patterns about how objects share work and talk to each other). When many objects all need to talk to each other, linking each one to every other one becomes a tangle. A mediator is one object in the middle that everyone talks through. We start with an airport control tower, watch a team chat silently lose a message, and invent the pattern as the fix. Then we hit an echo loop that crashes the program, build air-traffic control in Java, compare Mediator with Observer, and look at the danger of a god mediator. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: an airport control tower

At an airport In code
Planes landing, taking off, circling Colleagues: objects that must work together
The control tower: every pilot talks to it The mediator: the one object everyone talks through ("to mediate" = to stand in the middle and help others agree)
"Request landing", said to the tower, not to other planes A colleague knows only the mediator
"Hold" or "cleared to land": the tower decides The coordination logic lives in one place

Twenty planes each talking to nineteen others would be chaos. One tower keeps it simple.

2. The problem: everyone knows everyone

The team at Asha's cafe wants a small chat app. The obvious design: each User keeps a list of contacts, every other user, and send loops over them.

import java.util.*;
class User {
    final String name; final List<User> contacts = new ArrayList<>();  // knows other users
    User(String name) { this.name = name; }
    void connect(User other) { contacts.add(other); other.contacts.add(this); }
    void send(String msg) { for (User u : contacts) u.receive(name, msg); }
    void receive(String from, String msg) { System.out.println("  " + name + " got: " + msg); }
}
public class Main {
    public static void main(String[] args) {
        User asha = new User("Asha"), ravi = new User("Ravi");
        User neha = new User("Neha"), arjun = new User("Arjun");
        asha.connect(ravi); asha.connect(neha); ravi.connect(neha);    // everyone to everyone
        asha.connect(arjun); ravi.connect(arjun);                      // Arjun joins...
        System.out.println("Asha: Chai at 4?"); asha.send("Chai at 4?");
        System.out.println("Neha: Yes!");       neha.send("Yes!");
        int links = 0;
        for (User u : List.of(asha, ravi, neha, arjun)) links += u.contacts.size();
        System.out.println("links: " + links + ", with 100 users: " + 100 * 99);
    }
}

Output (real):

Asha: Chai at 4?
  Ravi got: Chai at 4?
  Neha got: Chai at 4?
  Arjun got: Chai at 4?
Neha: Yes!
  Asha got: Yes!
  Ravi got: Yes!
links: 10, with 100 users: 9900

Asha's question reaches everyone, but Neha's "Yes!" never reaches Arjun: when he joined, he was connected to Asha and Ravi, and nobody connected him to Neha. No error, no warning.

And the links: 4 users fully connected need 4 × 3 = 12 one-way links (we have 10, one connection is missing). 100 users need 100 × 99 = 9,900.

Why it failed

  • Many-to-many dependency: every user depends on many users, and many users depend on it.
  • Links grow like n × (n − 1); forgetting one silently loses messages.
  • Any rule (mute someone, private chats) would have to be added to every User.
  • That is tight coupling (episode 10): change one class, and many others must change with it.

3. The fix: a chat room in the middle

import java.util.*;
interface ChatMediator { void join(User u); void send(String msg, User from); }
class ChatRoom implements ChatMediator {                         // the mediator
    private final List<User> users = new ArrayList<>();
    public void join(User u) { users.add(u); }
    public void send(String msg, User from) {
        for (User u : users) if (u != from) u.receive(msg);      // the rule lives HERE
    }
    int links() { return users.size(); }
}
class User {                                                    // a colleague
    final String name; private final ChatMediator room;         // knows only the room
    User(String name, ChatMediator room) { this.name = name; this.room = room; room.join(this); }
    void send(String msg) { room.send(msg, this); }
    void receive(String msg) { System.out.println("  " + name + " got: " + msg); }
}
public class Main {
    public static void main(String[] args) {
        ChatRoom room = new ChatRoom();
        User asha = new User("Asha", room), ravi = new User("Ravi", room);
        User neha = new User("Neha", room), arjun = new User("Arjun", room);  // just join
        asha.send("Chai at 4?");
        neha.send("Yes!");
        System.out.println("links: " + room.links() + " (one per user)");
    }
}

Output (real):

  Ravi got: Chai at 4?
  Neha got: Chai at 4?
  Arjun got: Chai at 4?
  Asha got: Yes!
  Ravi got: Yes!
  Arjun got: Yes!
links: 4 (one per user)
  • ChatMediator is the mediator interface: how colleagues talk (join, send).
  • ChatRoom is the concrete mediator: it knows every user and holds the delivery rule ("everyone except the sender"). The rule lives here and only here.
  • User is a colleague: it holds one reference, the room. Its constructor joins the room; send hands the message to the room.
  • Users just join. No connect calls, nothing to forget, n links instead of n × (n − 1).

Muting a user or adding private messages now changes ChatRoom only. Users never decided who receives what, so they don't change.

4. It has a name: the Mediator pattern

                 ┌──────────────────────┐
   User ───────▶ │ ChatMediator          │ ◀- - - implements - - -  ChatRoom
 (colleague)     │ + join(u)             │                          - users: List<User>
   ▲             │ + send(msg, from)     │                          (concrete mediator: the rules)
   │ extends     └──────────────────────┘                                │ knows all
 Bot, Admin ...                                                           ▼
 (concrete colleagues)                                                  User, User, User ...
Role In our code Job
Mediator ChatMediator Defines how colleagues communicate
Concrete mediator ChatRoom, Tower Knows the colleagues, holds the coordination rules
Colleague User, Plane Knows only the mediator
Concrete colleagues Bot, Admin, ... Different kinds of participants

The classic intent (SourceMaking): "Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently." Many-to-many links become one-to-many: each colleague to one hub.

5. The trap: a bot that talks forever

An earlier ChatRoom delivered to every user, the sender included. Add a Bot that replies "Noted!" to everything:

import java.util.*;
class ChatRoom {                                                // the mediator
    private final List<User> users = new ArrayList<>();
    void join(User u) { users.add(u); }
    void send(String msg, User from) {
        for (User u : users) u.receive(msg);                    // everyone... even the sender
    }
}
class User {                                                    // a colleague
    final String name; final ChatRoom room;
    User(String name, ChatRoom room) { this.name = name; this.room = room; room.join(this); }
    void send(String msg) { room.send(msg, this); }
    void receive(String msg) { System.out.println("  " + name + " got: " + msg); }
}
class Bot extends User {                                        // replies to everything
    Bot(ChatRoom room) { super("Bot", room); }
    void receive(String msg) { send("Noted!"); }
}
public class Main {
    public static void main(String[] args) {
        ChatRoom room = new ChatRoom();
        new Bot(room);                                          // the bot joins first
        User asha = new User("Asha", room), ravi = new User("Ravi", room);
        System.out.println("Asha: Chai at 4?"); asha.send("Chai at 4?");
    }
}

Output (real):

Asha: Chai at 4?
Exception in thread "main" java.lang.StackOverflowError
    at ChatRoom.send(Main.java:6)
    at User.send(Main.java:12)
    at Bot.receive(Main.java:17)
    ... (more lines)

The bot's reply goes to the room; the room delivers it to everyone, including the bot; the bot replies to its own reply, forever. Each reply is one more method call waiting on the call stack (the memory that tracks unfinished method calls), until it runs out: StackOverflowError. Ravi never even got Asha's message.

The fix is one rule in one place: never deliver a message back to its sender.

import java.util.*;
class ChatRoom {                                                // the mediator
    private final List<User> users = new ArrayList<>();
    void join(User u) { users.add(u); }
    void send(String msg, User from) {
        for (User u : users) if (u != from) u.receive(msg);     // never back to the sender
    }
}
class User {                                                    // a colleague
    final String name; final ChatRoom room;
    User(String name, ChatRoom room) { this.name = name; this.room = room; room.join(this); }
    void send(String msg) { room.send(msg, this); }
    void receive(String msg) { System.out.println("  " + name + " got: " + msg); }
}
class Bot extends User {                                        // replies to everything
    Bot(ChatRoom room) { super("Bot", room); }
    void receive(String msg) { send("Noted!"); }
}
public class Main {
    public static void main(String[] args) {
        ChatRoom room = new ChatRoom();
        new Bot(room);                                          // the bot joins first
        User asha = new User("Asha", room), ravi = new User("Ravi", room);
        System.out.println("Asha: Chai at 4?"); asha.send("Chai at 4?");
    }
}

Output (real):

Asha: Chai at 4?
  Asha got: Noted!
  Ravi got: Noted!
  Ravi got: Chai at 4?

Notice the order: the bot is first in the room's list, so it hears "Chai at 4?" first and replies immediately; its "Noted!" reaches Asha and Ravi before the loop goes on to deliver Asha's question to Ravi. A mediator delivers one call at a time, and a reply made inside a delivery happens right away. If order matters, a mediator can queue messages and deliver them one after another instead.

6. Air-traffic control in code

import java.util.*;
class Tower {                                                   // the mediator
    private Plane onRunway; private final Deque<Plane> waiting = new ArrayDeque<>();
    void requestLanding(Plane p) {
        if (onRunway == null) { onRunway = p; p.cleared(); }
        else { waiting.add(p); System.out.println("  Tower: " + p.id + ", hold"); }
    }
    void landed(Plane p) {
        System.out.println("  Tower: " + p.id + " down, runway free");
        onRunway = waiting.poll(); if (onRunway != null) onRunway.cleared();
    }
}
class Plane {                                                   // a colleague
    final String id; private final Tower tower;                 // knows only the tower
    Plane(String id, Tower tower) { this.id = id; this.tower = tower; }
    void arrive() { System.out.println(id + ": request landing"); tower.requestLanding(this); }
    void cleared() { System.out.println("  Tower: " + id + ", cleared to land"); }
    void touchDown() { tower.landed(this); }
}
public class Main {
    public static void main(String[] args) {
        Tower t = new Tower();
        Plane a = new Plane("Flight 101", t), b = new Plane("Flight 202", t);
        Plane c = new Plane("Flight 303", t);
        a.arrive(); b.arrive(); c.arrive(); a.touchDown(); b.touchDown(); c.touchDown();
    }
}

Output (real):

Flight 101: request landing
  Tower: Flight 101, cleared to land
Flight 202: request landing
  Tower: Flight 202, hold
Flight 303: request landing
  Tower: Flight 303, hold
  Tower: Flight 101 down, runway free
  Tower: Flight 202, cleared to land
  Tower: Flight 202 down, runway free
  Tower: Flight 303, cleared to land
  Tower: Flight 303 down, runway free
  • Tower (mediator) remembers which plane is on the runway and keeps a queue of waiting planes (ArrayDeque, episode 4).
  • requestLanding: runway free → cleared; otherwise "hold" and join the queue.
  • landed: the runway is free; the next waiting plane, if any, is cleared.
  • Plane (colleague) knows only the tower. Planes never talk to planes, and there is never more than one plane on the runway.

The classic use: dialog boxes

The textbook motivation for the Mediator is a dialog window: picking a country in one box must refresh the state box and enable the PIN code box. Instead of widgets calling each other, a dialog mediator hears every widget change (widgetChanged(w)) and updates the others.

Practice 2 below builds a small, runnable version of this form mediator.

7. Mediator vs Observer

Observer (episode 35) Mediator
Shape one subject → many observers many colleagues ↔ one hub
Direction one-way: "I changed" two-way: ask, and get answers
Rules the subject doesn't care what observers do the hub holds the rules: who hears what, whose turn
Purpose spread news coordinate

They are often combined: colleagues notify the mediator (Observer), and the mediator decides what happens next.

8. The god-mediator risk

All coordination moves into the mediator, so it can grow into a god class (episode 12): one huge class that knows every detail and that every change touches.

Symptom Fix
Thousands of lines, knows every colleague's internals One mediator per job: a ChatRoom per room, a mediator per form
Every feature edits the mediator Keep the real work inside the colleagues; the hub only coordinates
Business rules mixed with routing Split routing (who talks to whom) from rules (what's allowed)

Use it when many objects interact in tangled ways. Skip it when two objects talk: a direct call is simpler.

Common mistakes

Mistake What you see Why Fix
Every object links to every other No error: a message silently lost n × (n − 1) links, one forgotten Talk through a mediator
Mediator delivers back to the sender java.lang.StackOverflowError A reply triggers a reply, forever Skip from when delivering
Colleagues still call each other directly No error: the hub's rules are skipped Two paths for the same message Colleagues know only the hub
One mediator for the whole app No error: a 3,000-line god class All logic piled into the hub One mediator per job
Mediator doing the colleagues' work Colleagues become empty data bags Logic in the wrong place The hub routes; colleagues act

Mini project: mute and private messages

import java.util.*;
class ChatRoom {                                               // the mediator
    private final Map<String, User> users = new LinkedHashMap<>();
    private final Set<String> muted = new HashSet<>();
    void join(User u) { users.put(u.name, u); }
    void mute(String name) { muted.add(name); }
    void send(String msg, User from) {
        if (muted.contains(from.name)) { System.out.println("  (" + from.name + " is muted)"); return; }
        if (msg.startsWith("@")) {                             // private: "@Neha text"
            String to = msg.substring(1, msg.indexOf(' '));
            User u = users.get(to);
            if (u == null) System.out.println("  (no user " + to + ")");
            else u.receive(from.name + " (private): " + msg.substring(msg.indexOf(' ') + 1));
            return;
        }
        for (User u : users.values()) if (u != from) u.receive(from.name + ": " + msg);
    }
}
class User {                                                   // a colleague
    final String name; private final ChatRoom room;
    User(String name, ChatRoom room) { this.name = name; this.room = room; room.join(this); }
    void send(String msg) { room.send(msg, this); }
    void receive(String msg) { System.out.println("  " + name + " got " + msg); }
}
public class Main {
    public static void main(String[] args) {
        ChatRoom room = new ChatRoom();
        User asha = new User("Asha", room), ravi = new User("Ravi", room), neha = new User("Neha", room);
        asha.send("Chai at 4?");
        ravi.send("@Neha are you coming?");
        room.mute("Ravi");
        ravi.send("Hello?");
        neha.send("@Arjun hi");
    }
}

Output (real):

  Ravi got Asha: Chai at 4?
  Neha got Asha: Chai at 4?
  Neha got Ravi (private): are you coming?
  (Ravi is muted)
  (no user Arjun)

Only ChatRoom changed; User is the same as before.

Practice

1. Add take-offs to the tower: a plane on the ground calls requestTakeoff(), and the tower lets it use the runway only when no plane is landing or taking off. Landings and take-offs share one waiting queue.

Answer
import java.util.*;
class Tower {                                                  // the mediator
    private Plane onRunway; private final Deque<Plane> waiting = new ArrayDeque<>();
    void request(Plane p, String what) {
        p.what = what;
        if (onRunway == null) { onRunway = p; System.out.println("  Tower: " + p.id + ", cleared to " + what); }
        else { waiting.add(p); System.out.println("  Tower: " + p.id + ", hold (" + what + ")"); }
    }
    void done(Plane p) {
        System.out.println("  Tower: " + p.id + " " + (p.what.equals("land") ? "down" : "airborne") + ", runway free");
        onRunway = waiting.poll();
        if (onRunway != null) System.out.println("  Tower: " + onRunway.id + ", cleared to " + onRunway.what);
    }
}
class Plane {                                                  // a colleague
    final String id; String what; private final Tower tower;
    Plane(String id, Tower tower) { this.id = id; this.tower = tower; }
    void requestLanding() { tower.request(this, "land"); }
    void requestTakeoff() { tower.request(this, "take off"); }
    void finished() { tower.done(this); }
}
public class Main {
    public static void main(String[] args) {
        Tower t = new Tower();
        Plane a = new Plane("Flight 101", t), b = new Plane("Flight 404", t);
        a.requestLanding(); b.requestTakeoff();
        a.finished(); b.finished();
    }
}

Output (real):

  Tower: Flight 101, cleared to land
  Tower: Flight 404, hold (take off)
  Tower: Flight 101 down, runway free
  Tower: Flight 404, cleared to take off
  Tower: Flight 404 airborne, runway free

2. Write a FormMediator: a country box and a state box. When the country changes to "India", the state box offers Kerala, Punjab, Gujarat; for any other country it is disabled. The boxes must not refer to each other.

Answer
import java.util.*;
class Box {                                                    // a colleague
    private final String name; private final FormMediator form; private String value = "";
    List<String> options = List.of(); boolean enabled = true;
    Box(String name, FormMediator form) { this.name = name; this.form = form; }
    void choose(String v) { value = v; System.out.println(name + " = " + v); form.changed(this); }
    String value() { return value; }
}
class FormMediator {                                           // the mediator
    final Box country = new Box("country", this), state = new Box("state", this);
    void changed(Box b) {
        if (b == country) {
            state.enabled = country.value().equals("India");
            state.options = state.enabled ? List.of("Kerala", "Punjab", "Gujarat") : List.of();
            System.out.println("  state box: " + (state.enabled ? state.options : "disabled"));
        }
    }
}
public class Main {
    public static void main(String[] args) {
        FormMediator f = new FormMediator();
        f.country.choose("India");
        f.country.choose("Nepal");
    }
}

Output (real):

country = India
  state box: [Kerala, Punjab, Gujarat]
country = Nepal
  state box: disabled

3. Count the links. 10 users, every user linked to every other (one-way links), versus a mediator.

Answer

Without a mediator: 10 × 9 = 90 one-way links (45 connections). With a mediator: 10 (each user → room), plus the room's own list of 10 users.

4. Why did the bot's "Noted!" arrive before Ravi got Asha's question in the fixed echo example? How could you make messages arrive in the order they were sent?

Answer

The room loops over users in join order; the bot is first, and its receive calls send immediately, so the nested delivery runs to completion before the outer loop reaches Ravi. To keep order, let the mediator put messages on a queue (ArrayDeque) and deliver them one by one in a loop; a reply sent during a delivery is added to the end of the queue instead of being delivered at once.

Quick quiz

// 50 users. Design A: each User keeps
//   a list of every other User.
// Design B: each User keeps one
//   reference to a ChatRoom.
// Links in A? Links in B?

(a) A: 50, B: 50 (b) A: 2,450, B: 50 (c) A: 2,500, B: 1 (d) A: 100, B: 50

Answer

(b) In A each user holds the 49 others: 50 × 49 = 2,450 one-way links. In B each user holds one link to the room: 50.

Interview questions

  1. What is the Mediator pattern? A behavioural pattern that defines an object which encapsulates how a set of objects interact, so they don't refer to each other directly.
  2. Participants? Mediator (interface), concrete mediator, colleagues (which know only the mediator).
  3. What problem does it solve? Many-to-many dependencies: n × (n − 1) links, rules scattered across classes, tight coupling.
  4. Real examples? Chat rooms, air-traffic control, dialog boxes/forms coordinating widgets, an event bus coordinating UI components, a game's match-making lobby.
  5. Mediator vs Observer? Observer broadcasts one-way from a subject to subscribers; a mediator coordinates two-way communication and holds the rules. A mediator is often implemented with observer-style notifications.
  6. Mediator vs Facade (episode 30)? A facade gives clients a simple interface to a subsystem, and the subsystem doesn't know about it. A mediator sits between peers that all know it and talk through it.
  7. Main risk? The god mediator: all logic accumulates in one class. Fix: one mediator per job, keep work in colleagues.
  8. How do you avoid echo loops? Never deliver a message back to its sender; optionally mark bot messages, or queue messages instead of delivering them inside other deliveries.
  9. How do you test it? Test the mediator with fake colleagues that record what they received; test colleagues with a fake mediator.
  10. When not to use it? When only two objects interact, or the interactions are simple and stable: direct calls are clearer.

Glossary

Term Meaning, with an example
Behavioural pattern A design pattern about how objects share work and talk to each other
Mediator The one object that colleagues talk through. The control tower, ChatRoom
Mediator pattern Put an object in the middle that encapsulates how a set of objects interact
Concrete mediator A real mediator class that knows the colleagues and holds the rules. ChatRoom, Tower
Colleague An object that takes part in the interaction and knows only the mediator. User, Plane
Many-to-many dependency Every object depends on many others, and many depend on it. Each user holding every other user
One-to-many Each colleague points to one hub; the hub points to many colleagues
Coupling How much one class depends on another; tight coupling means a change in one forces changes in others (episode 10)
Loose coupling Classes depend on little about each other, so they can change independently
Coordination logic The rules about who talks to whom and when. "Only one plane on the runway"
Chat room example Users send messages to a room, and the room delivers them
Air-traffic control example Planes ask a tower to land; the tower clears them one at a time
Echo loop A reply that triggers a reply, forever, because a message comes back to its sender
Call stack The memory that tracks unfinished method calls; too many nested calls cause StackOverflowError
StackOverflowError Thrown when the call stack runs out of room, usually from endless recursion
ArrayDeque A fast double-ended queue; used here as the waiting queue of planes (episode 4)
Observer pattern A subject notifies its subscribed observers when it changes (episode 35)
God class / god mediator One huge class that knows and does everything (episode 12)
Dialog-box example The classic motivation: a dialog mediator coordinates widgets such as a list box and a text field

Summary

  • When objects all talk to each other, links grow like n × (n − 1) and a forgotten link silently loses messages.
  • Mediator pattern: colleagues talk only to a mediator; the concrete mediator knows them all and holds the rules.
  • Never deliver back to the sender, or a replying colleague makes an echo loop (StackOverflowError).
  • Classic uses: chat rooms, air-traffic control, dialog boxes.
  • Observer spreads news one way; Mediator coordinates. Beware the god mediator: one mediator per job.

Next episode: The Memento pattern: save a snapshot of an object and restore it later, without breaking its privacy.