Mediator: The Hub in the Middle

When the front door has to turn off the alarm, turn on the hallway light and stop the music itself, every device knows several others and every new rule means opening a device's class; a Mediator lets each device tell the hub what happened, and only the hub knows who reacts.

Journeyman · OOP · Updated

By

After this lesson you can

  • Move the rules about which device reacts to which into one hub, so devices only talk to the hub
  • Spot the smells that point to Mediator: parts that each know and call several other parts

Key takeaways

  • The smell: parts that each hold and call several other parts, so a new rule means editing a part that shouldn't care.
  • The cause: the rules about who reacts to what are spread across the parts themselves.
  • The fix: each part tells one hub what happened; the hub holds every rule and tells the others what to do.
  • The modern version keeps the rules as data: for each event, a list of actions.
  • Skip it when two parts talk once and always will; and watch that the hub doesn't swallow the whole app.

Before this: Meet the Smart-Home Hub, and Facade: One Button, Many Parts, whose look-alike table first named Mediator.

When Maya unlocks the front door, two other things should happen: the alarm turns off and the hallway light comes on. When she locks it at night, the alarm arms, the hallway light goes off and the kitchen speaker stops. Right now the front door does all of that itself, so the door has to know the alarm, the light and the speaker. Next month a motion sensor arrives with rules of its own. This lesson is about the pattern that keeps devices from all knowing each other, the Mediator.

The symptom: the front door knows everyone

HallwayLight light = new HallwayLight();
Alarm alarm = new Alarm();
KitchenSpeaker speaker = new KitchenSpeaker();
FrontDoor door = new FrontDoor(light, alarm, speaker);

door.Unlock();
door.Lock();

class HallwayLight
{
    public void On() => Console.WriteLine("Hallway light: on");
    public void Off() => Console.WriteLine("Hallway light: off");
}

class Alarm
{
    public void Arm() => Console.WriteLine("Alarm: armed");
    public void Disarm() => Console.WriteLine("Alarm: off");
}

class KitchenSpeaker
{
    public void Stop() => Console.WriteLine("Kitchen speaker: stopped");
}

// The door does its own job, and everybody else's.
class FrontDoor
{
    private readonly HallwayLight light;
    private readonly Alarm alarm;
    private readonly KitchenSpeaker speaker;

    public FrontDoor(HallwayLight light, Alarm alarm, KitchenSpeaker speaker)
    {
        this.light = light;
        this.alarm = alarm;
        this.speaker = speaker;
    }

    public void Unlock()
    {
        Console.WriteLine("Front door: unlocked");
        alarm.Disarm();
        light.On();
    }

    public void Lock()
    {
        Console.WriteLine("Front door: locked");
        alarm.Arm();
        light.Off();
        speaker.Stop();
    }
}
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
    void on() { IO.println("Hallway light: on"); }
    void off() { IO.println("Hallway light: off"); }
}

class Alarm {
    void arm() { IO.println("Alarm: armed"); }
    void disarm() { IO.println("Alarm: off"); }
}

class KitchenSpeaker {
    void stop() { IO.println("Kitchen speaker: stopped"); }
}

// The door does its own job, and everybody else's.
class FrontDoor {
    private final HallwayLight light;
    private final Alarm alarm;
    private final KitchenSpeaker speaker;

    FrontDoor(HallwayLight light, Alarm alarm, KitchenSpeaker speaker) {
        this.light = light;
        this.alarm = alarm;
        this.speaker = speaker;
    }

    void unlock() {
        IO.println("Front door: unlocked");
        alarm.disarm();
        light.on();
    }

    void lock() {
        IO.println("Front door: locked");
        alarm.arm();
        light.off();
        speaker.stop();
    }
}

void main() {
    FrontDoor door = new FrontDoor(new HallwayLight(), new Alarm(), new KitchenSpeaker());
    door.unlock();
    door.lock();
}
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight:
    def on(self):
        print("Hallway light: on")

    def off(self):
        print("Hallway light: off")


class Alarm:
    def arm(self):
        print("Alarm: armed")

    def disarm(self):
        print("Alarm: off")


class KitchenSpeaker:
    def stop(self):
        print("Kitchen speaker: stopped")


class FrontDoor:
    """The door does its own job, and everybody else's."""

    def __init__(self, light, alarm, speaker):
        self.light = light
        self.alarm = alarm
        self.speaker = speaker

    def unlock(self):
        print("Front door: unlocked")
        self.alarm.disarm()
        self.light.on()

    def lock(self):
        print("Front door: locked")
        self.alarm.arm()
        self.light.off()
        self.speaker.stop()


door = FrontDoor(HallwayLight(), Alarm(), KitchenSpeaker())
door.unlock()
door.lock()
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
  on() { console.log("Hallway light: on"); }
  off() { console.log("Hallway light: off"); }
}

class Alarm {
  arm() { console.log("Alarm: armed"); }
  disarm() { console.log("Alarm: off"); }
}

class KitchenSpeaker {
  stop() { console.log("Kitchen speaker: stopped"); }
}

// The door does its own job, and everybody else's.
class FrontDoor {
  #light;
  #alarm;
  #speaker;
  constructor(light, alarm, speaker) {
    this.#light = light;
    this.#alarm = alarm;
    this.#speaker = speaker;
  }

  unlock() {
    console.log("Front door: unlocked");
    this.#alarm.disarm();
    this.#light.on();
  }

  lock() {
    console.log("Front door: locked");
    this.#alarm.arm();
    this.#light.off();
    this.#speaker.stop();
  }
}

const door = new FrontDoor(new HallwayLight(), new Alarm(), new KitchenSpeaker());
door.unlock();
door.lock();
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
  on(): void { console.log("Hallway light: on"); }
  off(): void { console.log("Hallway light: off"); }
}

class Alarm {
  arm(): void { console.log("Alarm: armed"); }
  disarm(): void { console.log("Alarm: off"); }
}

class KitchenSpeaker {
  stop(): void { console.log("Kitchen speaker: stopped"); }
}

// The door does its own job, and everybody else's.
class FrontDoor {
  #light: HallwayLight;
  #alarm: Alarm;
  #speaker: KitchenSpeaker;
  constructor(light: HallwayLight, alarm: Alarm, speaker: KitchenSpeaker) {
    this.#light = light;
    this.#alarm = alarm;
    this.#speaker = speaker;
  }

  unlock(): void {
    console.log("Front door: unlocked");
    this.#alarm.disarm();
    this.#light.on();
  }

  lock(): void {
    console.log("Front door: locked");
    this.#alarm.arm();
    this.#light.off();
    this.#speaker.stop();
  }
}

const door = new FrontDoor(new HallwayLight(), new Alarm(), new KitchenSpeaker());
door.unlock();
door.lock();
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped

The door is a lock, but its class is mostly about lights, alarms and music. "Stop the music when the door locks" is a rule about the house, and it lives inside the door. When the motion sensor arrives ("motion in the hallway at night: light on, and if the alarm is armed, sound it"), the sensor will need the light and the alarm too, and the alarm will soon need the speaker. Four devices that all know each other means up to six connections; six devices, fifteen. And you can't use this FrontDoor in the apartment of Maya's sister, which has no alarm.

  • The symptom: parts that each hold and call several other parts, and new rules that mean editing a part that shouldn't care.
  • The cause: the rules about who reacts to what are spread across the devices. No one place says "when the door locks, this happens".

What would you try?

A big "house" class that every device can reach. Each device calls house.alarm.arm() itself. The door no longer holds the alarm, but it still decides that the alarm arms: the rule is still in the door.

Copy the rule into each device that needs it. The motion sensor gets its own "if the alarm is armed" code. Now the same rule lives in two places, and they'll drift apart.

Let every device tell every other device what happened, and let each decide. That's the same web of connections, with messages instead of calls.

What we want is one place that holds the rules, and devices that only report what happened to them.

The fix: one hub in the middle

A wedding planner works like this. The caterer, the band and the florist never call each other. Each tells the planner what's going on ("the cake is late", "the band needs power at six"), and the planner, who knows the whole plan, tells whoever has to react. Add a photographer, and only the planner has to learn about them.

A wedding planner standing in the middle of a reception hall with a clipboard, connected by lines to a caterer with a cake, a band with instruments, and a florist with flowers; the three of them aren't connected to each other, only to the planner

The hub does the same for devices. Each device tells the hub what happened to it, "front door unlocked", and nothing more. The hub holds every rule and tells the devices that should react. The devices no longer know each other; each knows only the hub.

Two ways to wire four devices (front door, hallway light, alarm, kitchen speaker). Left, every device knows the others: a line between every pair, six lines. Right, each device knows only the hub: four lines, one from each device to the hub

Mediator's roles: the front door tells the hub "front door locked", and the hub, which holds the rules, tells the alarm, the hallway light and the kitchen speaker. The hub sits in a dashed fence labeled "what changes: the rules about who reacts"

The classic version: devices tell the hub

The door now holds only the hub, and says what happened. The hub decides:

HallwayLight light = new HallwayLight();
Alarm alarm = new Alarm();
KitchenSpeaker speaker = new KitchenSpeaker();
Hub hub = new Hub(light, alarm, speaker);
FrontDoor door = new FrontDoor(hub);

door.Unlock();
door.Lock();

// The only place that knows who reacts to what.
class Hub
{
    private readonly HallwayLight light;
    private readonly Alarm alarm;
    private readonly KitchenSpeaker speaker;

    public Hub(HallwayLight light, Alarm alarm, KitchenSpeaker speaker)
    {
        this.light = light;
        this.alarm = alarm;
        this.speaker = speaker;
    }

    public void Notify(string what)
    {
        if (what == "front door unlocked")
        {
            alarm.Disarm();
            light.On();
        }
        else if (what == "front door locked")
        {
            alarm.Arm();
            light.Off();
            speaker.Stop();
        }
    }
}

// The door does its own job, and tells the hub.
class FrontDoor
{
    private readonly Hub hub;
    public FrontDoor(Hub hub) { this.hub = hub; }

    public void Unlock()
    {
        Console.WriteLine("Front door: unlocked");
        hub.Notify("front door unlocked");
    }

    public void Lock()
    {
        Console.WriteLine("Front door: locked");
        hub.Notify("front door locked");
    }
}

class HallwayLight
{
    public void On() => Console.WriteLine("Hallway light: on");
    public void Off() => Console.WriteLine("Hallway light: off");
}

class Alarm
{
    public void Arm() => Console.WriteLine("Alarm: armed");
    public void Disarm() => Console.WriteLine("Alarm: off");
}

class KitchenSpeaker
{
    public void Stop() => Console.WriteLine("Kitchen speaker: stopped");
}
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
    void on() { IO.println("Hallway light: on"); }
    void off() { IO.println("Hallway light: off"); }
}

class Alarm {
    void arm() { IO.println("Alarm: armed"); }
    void disarm() { IO.println("Alarm: off"); }
}

class KitchenSpeaker {
    void stop() { IO.println("Kitchen speaker: stopped"); }
}

// The only place that knows who reacts to what.
class Hub {
    private final HallwayLight light;
    private final Alarm alarm;
    private final KitchenSpeaker speaker;

    Hub(HallwayLight light, Alarm alarm, KitchenSpeaker speaker) {
        this.light = light;
        this.alarm = alarm;
        this.speaker = speaker;
    }

    void notify(String what) {
        if (what.equals("front door unlocked")) {
            alarm.disarm();
            light.on();
        } else if (what.equals("front door locked")) {
            alarm.arm();
            light.off();
            speaker.stop();
        }
    }
}

// The door does its own job, and tells the hub.
class FrontDoor {
    private final Hub hub;
    FrontDoor(Hub hub) { this.hub = hub; }

    void unlock() {
        IO.println("Front door: unlocked");
        hub.notify("front door unlocked");
    }

    void lock() {
        IO.println("Front door: locked");
        hub.notify("front door locked");
    }
}

void main() {
    Hub hub = new Hub(new HallwayLight(), new Alarm(), new KitchenSpeaker());
    FrontDoor door = new FrontDoor(hub);
    door.unlock();
    door.lock();
}
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight:
    def on(self):
        print("Hallway light: on")

    def off(self):
        print("Hallway light: off")


class Alarm:
    def arm(self):
        print("Alarm: armed")

    def disarm(self):
        print("Alarm: off")


class KitchenSpeaker:
    def stop(self):
        print("Kitchen speaker: stopped")


class Hub:
    """The only place that knows who reacts to what."""

    def __init__(self, light, alarm, speaker):
        self.light = light
        self.alarm = alarm
        self.speaker = speaker

    def notify(self, what):
        if what == "front door unlocked":
            self.alarm.disarm()
            self.light.on()
        elif what == "front door locked":
            self.alarm.arm()
            self.light.off()
            self.speaker.stop()


class FrontDoor:
    """The door does its own job, and tells the hub."""

    def __init__(self, hub):
        self.hub = hub

    def unlock(self):
        print("Front door: unlocked")
        self.hub.notify("front door unlocked")

    def lock(self):
        print("Front door: locked")
        self.hub.notify("front door locked")


hub = Hub(HallwayLight(), Alarm(), KitchenSpeaker())
door = FrontDoor(hub)
door.unlock()
door.lock()
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
  on() { console.log("Hallway light: on"); }
  off() { console.log("Hallway light: off"); }
}

class Alarm {
  arm() { console.log("Alarm: armed"); }
  disarm() { console.log("Alarm: off"); }
}

class KitchenSpeaker {
  stop() { console.log("Kitchen speaker: stopped"); }
}

// The only place that knows who reacts to what.
class Hub {
  #light;
  #alarm;
  #speaker;
  constructor(light, alarm, speaker) {
    this.#light = light;
    this.#alarm = alarm;
    this.#speaker = speaker;
  }

  notify(what) {
    if (what === "front door unlocked") {
      this.#alarm.disarm();
      this.#light.on();
    } else if (what === "front door locked") {
      this.#alarm.arm();
      this.#light.off();
      this.#speaker.stop();
    }
  }
}

// The door does its own job, and tells the hub.
class FrontDoor {
  #hub;
  constructor(hub) { this.#hub = hub; }

  unlock() {
    console.log("Front door: unlocked");
    this.#hub.notify("front door unlocked");
  }

  lock() {
    console.log("Front door: locked");
    this.#hub.notify("front door locked");
  }
}

const hub = new Hub(new HallwayLight(), new Alarm(), new KitchenSpeaker());
const door = new FrontDoor(hub);
door.unlock();
door.lock();
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
  on(): void { console.log("Hallway light: on"); }
  off(): void { console.log("Hallway light: off"); }
}

class Alarm {
  arm(): void { console.log("Alarm: armed"); }
  disarm(): void { console.log("Alarm: off"); }
}

class KitchenSpeaker {
  stop(): void { console.log("Kitchen speaker: stopped"); }
}

// The only place that knows who reacts to what.
class Hub {
  #light: HallwayLight;
  #alarm: Alarm;
  #speaker: KitchenSpeaker;
  constructor(light: HallwayLight, alarm: Alarm, speaker: KitchenSpeaker) {
    this.#light = light;
    this.#alarm = alarm;
    this.#speaker = speaker;
  }

  notify(what: string): void {
    if (what === "front door unlocked") {
      this.#alarm.disarm();
      this.#light.on();
    } else if (what === "front door locked") {
      this.#alarm.arm();
      this.#light.off();
      this.#speaker.stop();
    }
  }
}

// The door does its own job, and tells the hub.
class FrontDoor {
  #hub: Hub;
  constructor(hub: Hub) { this.#hub = hub; }

  unlock(): void {
    console.log("Front door: unlocked");
    this.#hub.notify("front door unlocked");
  }

  lock(): void {
    console.log("Front door: locked");
    this.#hub.notify("front door locked");
  }
}

const hub = new Hub(new HallwayLight(), new Alarm(), new KitchenSpeaker());
const door = new FrontDoor(hub);
door.unlock();
door.lock();
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped

The output is the same; the knowledge moved. The door knows one thing, the hub, and the house's rules are all in notify, where you can read them in one place. The door works in her sister's apartment too: hand it a hub with that apartment's rules. The motion sensor will be one more device that tells the hub, plus its rules in the hub.

The modern version: the rules as data

The if/else if in notify grows with every rule. The rules can be data instead: for each event, a list of things to do. Setting up the house is then a list of when lines:

HallwayLight light = new HallwayLight();
Alarm alarm = new Alarm();
KitchenSpeaker speaker = new KitchenSpeaker();

Hub hub = new Hub();
hub.When("front door unlocked", alarm.Disarm, light.On);
hub.When("front door locked", alarm.Arm, light.Off, speaker.Stop);

FrontDoor door = new FrontDoor(hub);
door.Unlock();
door.Lock();

// The rules are data: for each event, the actions that follow it.
class Hub
{
    private readonly Dictionary<string, List<Action>> rules = new Dictionary<string, List<Action>>();

    public void When(string what, params Action[] actions)
    {
        if (!rules.ContainsKey(what))
        {
            rules[what] = new List<Action>();
        }
        rules[what].AddRange(actions);
    }

    public void Notify(string what)
    {
        foreach (Action action in rules.GetValueOrDefault(what, new List<Action>()))
        {
            action();
        }
    }
}

class FrontDoor
{
    private readonly Hub hub;
    public FrontDoor(Hub hub) { this.hub = hub; }

    public void Unlock()
    {
        Console.WriteLine("Front door: unlocked");
        hub.Notify("front door unlocked");
    }

    public void Lock()
    {
        Console.WriteLine("Front door: locked");
        hub.Notify("front door locked");
    }
}

class HallwayLight
{
    public void On() => Console.WriteLine("Hallway light: on");
    public void Off() => Console.WriteLine("Hallway light: off");
}

class Alarm
{
    public void Arm() => Console.WriteLine("Alarm: armed");
    public void Disarm() => Console.WriteLine("Alarm: off");
}

class KitchenSpeaker
{
    public void Stop() => Console.WriteLine("Kitchen speaker: stopped");
}
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
    void on() { IO.println("Hallway light: on"); }
    void off() { IO.println("Hallway light: off"); }
}

class Alarm {
    void arm() { IO.println("Alarm: armed"); }
    void disarm() { IO.println("Alarm: off"); }
}

class KitchenSpeaker {
    void stop() { IO.println("Kitchen speaker: stopped"); }
}

// The rules are data: for each event, the actions that follow it.
class Hub {
    private final Map<String, List<Runnable>> rules = new HashMap<>();

    void when(String what, Runnable... actions) {
        rules.computeIfAbsent(what, key -> new ArrayList<>()).addAll(List.of(actions));
    }

    void notify(String what) {
        for (Runnable action : rules.getOrDefault(what, List.of())) {
            action.run();
        }
    }
}

class FrontDoor {
    private final Hub hub;
    FrontDoor(Hub hub) { this.hub = hub; }

    void unlock() {
        IO.println("Front door: unlocked");
        hub.notify("front door unlocked");
    }

    void lock() {
        IO.println("Front door: locked");
        hub.notify("front door locked");
    }
}

void main() {
    HallwayLight light = new HallwayLight();
    Alarm alarm = new Alarm();
    KitchenSpeaker speaker = new KitchenSpeaker();

    Hub hub = new Hub();
    hub.when("front door unlocked", alarm::disarm, light::on);
    hub.when("front door locked", alarm::arm, light::off, speaker::stop);

    FrontDoor door = new FrontDoor(hub);
    door.unlock();
    door.lock();
}
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight:
    def on(self):
        print("Hallway light: on")

    def off(self):
        print("Hallway light: off")


class Alarm:
    def arm(self):
        print("Alarm: armed")

    def disarm(self):
        print("Alarm: off")


class KitchenSpeaker:
    def stop(self):
        print("Kitchen speaker: stopped")


class Hub:
    """The rules are data: for each event, the actions that follow it."""

    def __init__(self):
        self.rules = {}

    def when(self, what, *actions):
        self.rules.setdefault(what, []).extend(actions)

    def notify(self, what):
        for action in self.rules.get(what, []):
            action()


class FrontDoor:
    def __init__(self, hub):
        self.hub = hub

    def unlock(self):
        print("Front door: unlocked")
        self.hub.notify("front door unlocked")

    def lock(self):
        print("Front door: locked")
        self.hub.notify("front door locked")


light, alarm, speaker = HallwayLight(), Alarm(), KitchenSpeaker()

hub = Hub()
hub.when("front door unlocked", alarm.disarm, light.on)
hub.when("front door locked", alarm.arm, light.off, speaker.stop)

door = FrontDoor(hub)
door.unlock()
door.lock()
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
  on() { console.log("Hallway light: on"); }
  off() { console.log("Hallway light: off"); }
}

class Alarm {
  arm() { console.log("Alarm: armed"); }
  disarm() { console.log("Alarm: off"); }
}

class KitchenSpeaker {
  stop() { console.log("Kitchen speaker: stopped"); }
}

// The rules are data: for each event, the actions that follow it.
class Hub {
  #rules = new Map();

  when(what, ...actions) {
    this.#rules.set(what, [...(this.#rules.get(what) ?? []), ...actions]);
  }

  notify(what) {
    for (const action of this.#rules.get(what) ?? []) action();
  }
}

class FrontDoor {
  #hub;
  constructor(hub) { this.#hub = hub; }

  unlock() {
    console.log("Front door: unlocked");
    this.#hub.notify("front door unlocked");
  }

  lock() {
    console.log("Front door: locked");
    this.#hub.notify("front door locked");
  }
}

const light = new HallwayLight();
const alarm = new Alarm();
const speaker = new KitchenSpeaker();

const hub = new Hub();
hub.when("front door unlocked", () => alarm.disarm(), () => light.on());
hub.when("front door locked", () => alarm.arm(), () => light.off(), () => speaker.stop());

const door = new FrontDoor(hub);
door.unlock();
door.lock();
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped
class HallwayLight {
  on(): void { console.log("Hallway light: on"); }
  off(): void { console.log("Hallway light: off"); }
}

class Alarm {
  arm(): void { console.log("Alarm: armed"); }
  disarm(): void { console.log("Alarm: off"); }
}

class KitchenSpeaker {
  stop(): void { console.log("Kitchen speaker: stopped"); }
}

// The rules are data: for each event, the actions that follow it.
class Hub {
  #rules = new Map<string, Array<() => void>>();

  when(what: string, ...actions: Array<() => void>): void {
    this.#rules.set(what, [...(this.#rules.get(what) ?? []), ...actions]);
  }

  notify(what: string): void {
    for (const action of this.#rules.get(what) ?? []) action();
  }
}

class FrontDoor {
  #hub: Hub;
  constructor(hub: Hub) { this.#hub = hub; }

  unlock(): void {
    console.log("Front door: unlocked");
    this.#hub.notify("front door unlocked");
  }

  lock(): void {
    console.log("Front door: locked");
    this.#hub.notify("front door locked");
  }
}

const light = new HallwayLight();
const alarm = new Alarm();
const speaker = new KitchenSpeaker();

const hub = new Hub();
hub.when("front door unlocked", () => alarm.disarm(), () => light.on());
hub.when("front door locked", () => alarm.arm(), () => light.off(), () => speaker.stop());

const door = new FrontDoor(hub);
door.unlock();
door.lock();
Front door: unlocked
Alarm: off
Hallway light: on
Front door: locked
Alarm: armed
Hallway light: off
Kitchen speaker: stopped

Same seven lines. The hub's code no longer names any device; the house's rules are the when lines, all in one place, and a new rule is one more line there. This looks a lot like Pass 1's Observer (a list of things to call), and it's close kin: the difference is who decides. With Observer, each listener chooses to subscribe. With a Mediator, the rules of the house are written in one place, the hub's setup, and the devices don't take part in deciding.

How it got its name

A mediator is someone who stands between two sides so they don't have to deal with each other directly. In code, a mediator is the one object that parts talk through, so they don't talk to each other. Teams building screens full of controls kept hitting the same tangle (this box enables that button, which clears that list), kept landing on "let the screen decide", and the fix went into the original 1994 book as the Mediator pattern. Pass 1's Facade lesson met it in a look-alike table: a facade is called by outside code and the parts never call it back; a mediator is called by the parts themselves.

Where you've already used it

  • A chat room: you send your message to the room, and the room delivers it to everyone in it; you never connect to each person.
  • A form on a screen where checking "same as shipping address" fills in and greys out the billing fields: the form decides, not the checkbox.
  • A group's shared calendar: you put a meeting on it, and it tells everyone invited; nobody phones each guest.

When not to use it

  • When two parts talk once, and always will. A door that calls one light is fine; a hub in between is ceremony.
  • When the hub starts doing the devices' jobs. The hub decides who reacts; the alarm still knows how to arm itself. A hub that holds every rule and every device's work becomes a god class, the smell Pass 5 opens with.
  • When the parts really are a sequence, such as checks that must run in order: that's the last lesson's chain.

The cost: the rules are in one place, which is the point, and also the risk: that one place can grow very large. Split it by area (the front door's rules, the bedroom's rules) before it does.

How often you'll meet it: now and then (our estimate: in apps with many screens or devices that react to each other, and inside many frameworks' screen code).

Check yourself

2 questions to try on the lesson page.

So what

When every part holds and calls several others, give them one hub to tell what happened. The parts stay simple and reusable, the rules of the house live in one place, and the next device only has to know the hub.

Key terms

Cheat sheets