Skip to content

Mediator: Route Component Chatter Through One Coordinator

Learn the Mediator pattern by refactoring a coffee roaster's firmware so the probe, burner, door and fan stop calling each other directly.

12 min readDesign patternBehavioural

Define an object that encapsulates how a set of components interact, so the components no longer refer to each other explicitly. You can then change the interaction rules in one place and reuse each component on its own.

Mediator is the pattern you reach for when a handful of objects have grown a tangle of direct references to each other. Instead of every component knowing every other component, each one reports to a single coordinator, and the coordinator decides who reacts. In this guide you follow one firmware team through that refactoring. You will see the coupled version, the mediated version, a class diagram, pseudocode, and runnable code in TypeScript, Python and PHP. You will also see the trade-off interviewers usually ask about: the coordinator itself can turn into a god object if you are careless.

The problem

A situation where the obvious design starts to hurt.

Ember Lane is a roastery with 6 drum roasters, each driven by firmware written by a three-person team. A roaster has four parts that matter during a batch: a temperature probe, a gas burner, a drum door that drops the beans into the cooling tray, and a cooling fan.

The first firmware version wired these parts together directly. The probe held references to the burner and the door: at 190C it called burner.setLevel(40) to slow the roast, and at 210C it called burner.off() and door.open(). The door held a reference to the fan and started it when it opened. The burner held a reference to the probe so it could check the temperature before relighting.

With four parts there are already up to 12 directed links, and every rule about the roast lives inside whichever part happens to notice the condition first. When the head roaster asked for a different profile on the decaf machine, with a 205C drop instead of 210C, the team had to edit the probe class, which should only read temperatures. When they wanted to reuse the same door class on a new sample roaster that has no fan, they could not, because the door imported the fan. Adding a planned smoke sensor would mean touching the probe, the burner and the door again. Each part was hard to test alone, because constructing one required constructing all the others.

The solution

What the pattern proposes.

Move the rules out of the parts and into one object that knows all of them: a RoastController that implements a small RoastMediator interface with a single method, notify(sender, event).

Each part now holds only a reference to the mediator interface. The probe records a reading and calls notify(this, "temperature"). The door opens and calls notify(this, "doorOpened"). The burner and the fan just expose commands such as setLevel, off and start; they do not know who calls them.

The controller receives every notification and applies the roast profile: at the development threshold it lowers the burner to 40%, at the drop threshold it turns the burner off and opens the door, and when the door reports it has opened it starts the fan. The decaf profile becomes a controller configured with dropAt = 205. The sample roaster without a fan gets a different controller, and the door class is reused unchanged. The smoke sensor, when it arrives, becomes one more component plus one more branch in the controller, and no existing part changes.

The many-to-many web of references becomes a star: four parts pointing at one coordinator, and the coordinator pointing back at the parts it needs to command.

An everyday analogy

The same idea, outside software.

Think of a busy restaurant pass. Cooks at the grill, the fryer and the salad station do not shout at each other about timing. Each one tells the expediter when a component is ready, and the expediter decides when to fire the next dish, when to hold the fries, and when a plate goes out. A new cook can join the line knowing only how to talk to the expediter. The cost is that the expediter has to understand the whole menu, and if that person is overloaded, the whole kitchen slows down.

Structure

The pieces and how they relate.

Roaster parts report events to RoastController through the RoastMediator interface; only the controller commands other parts.Firmware main creates RoastController. RoastController implements RoastMediator. Component calls RoastMediator (notify()). TemperatureProbe inherits from Component. Burner inherits from Component. DrumDoor inherits from Component. CoolingFan inherits from Component. RoastController calls Burner (setLevel / off). RoastController calls DrumDoor (open). RoastController calls CoolingFan (start). RoastController has a TemperatureProbe (reads lastReading).Firmware mainwires parts to acontroller«interface»RoastMediatornotify(sender,event)RoastControllerdropAt, developAt,roast rules«abstract»Componentmediator,setMediator()TemperatureProberead(celsius),lastReadingBurnersetLevel(percent),off()DrumDooropen(), isOpenCoolingFanstart(), runningNo partreference…all coordinationlives in th…notify()setLevel / offopenstartreads lastReading
Roaster parts report events to RoastController through the RoastMediator interface; only the controller commands other parts.

Participants

RoastMediator (Mediator interface)
Declares the single method parts use to report what happened: notify(sender, event). Parts depend on this interface, not on the concrete controller.
RoastController (Concrete Mediator)
Holds references to every part and owns the roast rules. It reacts to notifications by commanding other parts. Thresholds such as dropAt and developAt live here.
Component (base class)
Stores the mediator reference and lets it be set after construction, so parts can be built independently and wired later.
TemperatureProbe, Burner, DrumDoor, CoolingFan (Concrete Components)
Do one job each. They report events to the mediator and expose commands, but never call each other.
Firmware main (Client)
Creates the parts, creates the controller with the right profile, and starts feeding probe readings.

Pseudocode

The solution to the scenario, language-neutral.

interface RoastMediator
    method notify(sender, event)

abstract class Component
    field mediator
    method setMediator(m)
        mediator = m

class TemperatureProbe extends Component
    field lastReading = 0
    method read(celsius)
        lastReading = celsius
        log "probe: " + celsius + "C"
        mediator.notify(this, "temperature")

class Burner extends Component
    field level = 100
    method setLevel(percent)
        level = percent
        log "burner: level " + percent + "%"
    method off()
        setLevel(0)

class DrumDoor extends Component
    field isOpen = false
    method open()
        if isOpen then return
        isOpen = true
        log "door: open"
        mediator.notify(this, "doorOpened")

class CoolingFan extends Component
    field running = false
    method start()
        running = true
        log "fan: on"

class RoastController implements RoastMediator
    constructor(probe, burner, door, fan, dropAt = 210, developAt = 190)
        store all fields
        for each part in [probe, burner, door, fan]
            part.setMediator(this)

    method notify(sender, event)
        if sender is probe and event is "temperature"
            onTemperature(probe.lastReading)
        else if sender is door and event is "doorOpened"
            fan.start()

    method onTemperature(celsius)
        if celsius >= dropAt
            burner.off()
            door.open()
        else if celsius >= developAt and burner.level > 40
            burner.setLevel(40)

// client
probe = new TemperatureProbe()
new RoastController(probe, new Burner(), new DrumDoor(), new CoolingFan())
probe.read(150)
probe.read(192)
probe.read(211)

The code

The same solution in TypeScript, Python and PHP.

type RoastEvent = "temperature" | "doorOpened";

interface RoastMediator {
  notify(sender: Component, event: RoastEvent): void;
}

abstract class Component {
  protected mediator: RoastMediator | null = null;

  setMediator(mediator: RoastMediator): void {
    this.mediator = mediator;
  }
}

class TemperatureProbe extends Component {
  lastReading = 0;

  read(celsius: number): void {
    this.lastReading = celsius;
    console.log(`probe: ${celsius}C`);
    this.mediator?.notify(this, "temperature");
  }
}

class Burner extends Component {
  level = 100;

  setLevel(percent: number): void {
    this.level = percent;
    console.log(`burner: level ${percent}%`);
  }

  off(): void {
    this.setLevel(0);
  }
}

class DrumDoor extends Component {
  isOpen = false;

  open(): void {
    if (this.isOpen) return;
    this.isOpen = true;
    console.log("door: open");
    this.mediator?.notify(this, "doorOpened");
  }
}

class CoolingFan extends Component {
  running = false;

  start(): void {
    this.running = true;
    console.log("fan: on");
  }
}

class RoastController implements RoastMediator {
  constructor(
    private readonly probe: TemperatureProbe,
    private readonly burner: Burner,
    private readonly door: DrumDoor,
    private readonly fan: CoolingFan,
    private readonly dropAt = 210,
    private readonly developAt = 190,
  ) {
    for (const part of [probe, burner, door, fan]) {
      part.setMediator(this);
    }
  }

  notify(sender: Component, event: RoastEvent): void {
    if (sender === this.probe && event === "temperature") {
      this.onTemperature(this.probe.lastReading);
    } else if (sender === this.door && event === "doorOpened") {
      this.fan.start();
    }
  }

  private onTemperature(celsius: number): void {
    if (celsius >= this.dropAt) {
      this.burner.off();
      this.door.open();
    } else if (celsius >= this.developAt && this.burner.level > 40) {
      this.burner.setLevel(40);
    }
  }
}

const probe = new TemperatureProbe();
new RoastController(probe, new Burner(), new DrumDoor(), new CoolingFan());

probe.read(150);
probe.read(192);
probe.read(211);
// probe: 150C
// probe: 192C
// burner: level 40%
// probe: 211C
// burner: level 0%
// door: open
// fan: on

When to use it

Situations where it pays off.

  • Several objects reference each other directly and a change to one forces edits in the others.

    A mediator replaces the many-to-many links with one-to-many links. Each part depends only on the mediator interface, so you can change or replace a part without touching its former neighbours.

  • You want to reuse a component in a different context, but it drags its collaborators along.

    Once the door only knows a RoastMediator, it can be dropped into a sample roaster with no fan. The new context supplies its own controller with its own rules.

  • The same set of parts needs different interaction rules in different products or configurations.

    Each rule set becomes a separate concrete mediator, or one mediator with different settings, such as a decaf controller that drops at 205C. The parts stay identical.

  • The behaviour you care about is the coordination itself, and it is currently scattered across many classes.

    Putting the rules in one class makes them readable in one place and testable with fake components, which is far easier than reconstructing the sequence from calls spread over four files.

How to implement it

Steps to introduce it in existing code.

  1. List the components that call each other and write down each interaction as a rule: when X happens, Y and Z must react. These rules become the body of the mediator.

  2. Define a mediator interface with a notification method, usually notify(sender, event). Keep it small so components stay unaware of the concrete coordinator.

  3. Give components a reference to the mediator interface, typically through a base class with setMediator, and remove their direct references to each other.

  4. Replace each direct cross-call inside a component with a call to mediator.notify(this, event). The component reports what happened, not what others should do.

  5. Implement the concrete mediator: hold references to the components, and in notify branch on sender and event to command the right components.

  6. Let the client create the components, then the mediator, and wire them. Move configuration that describes coordination, such as thresholds, into the mediator.

  7. Write tests for the mediator with simple fake components, and tests for each component with a fake mediator that records notifications.

  8. Watch the mediator's size. When it starts handling unrelated concerns, split it by concern or by phase rather than letting it absorb everything.

Pros and cons

What you gain and what you pay.

Pros

  • Components no longer depend on each other, so each can be built, tested and reused on its own.
  • Interaction rules live in one class, which makes them easy to read, review and change.
  • You can swap the coordination logic by supplying a different mediator without modifying any component.
  • Adding a component usually means one new class and a few new branches in the mediator, with no edits to existing components.
  • Removes the many-to-many reference web, which shrinks the number of dependencies you have to reason about.

Cons

  • The mediator can grow into a god object that knows too much and changes for too many reasons.
  • Control flow becomes less direct: to see what happens after the probe reads 211C, you have to read the mediator, not the probe.
  • Notifications keyed on string events are easy to mistype and are not checked by the compiler unless you use enums or typed event objects.
  • The mediator becomes a single point where a bug affects every interaction, so it needs good test coverage.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

How is Mediator different from Observer?

Observer is a subscription mechanism: a subject broadcasts to whoever registered, and it does not care what they do. Mediator is about where the coordination rules live: one object knows the participants and decides who reacts to what. You can implement a mediator with Observer-style events, but the defining feature is the central decision-maker, not the broadcast.

Doesn't the mediator just become a god object?

It can, and interviewers like to hear you name that risk. Keep the mediator focused on one interaction scope, such as a single roaster's batch cycle. If it starts handling logging, billing and maintenance schedules too, split it by concern. A mediator full of roast rules is fine; a mediator that knows everything in the building is not.

Should components pass string events or typed messages?

Strings are the shortest way to show the pattern, which is why the sample uses a union type in TypeScript and a Literal in Python to catch typos. In larger systems, prefer enums or small event objects that carry data, such as a TemperatureRead with the reading, so the mediator does not need to query the sender afterwards.

Why does the door notify the mediator instead of starting the fan itself?

Because the rule that the fan starts when the door opens belongs to this roaster, not to doors in general. Keeping the door ignorant of the fan lets you reuse it on a sample roaster with no fan, where a different controller handles the door event differently or ignores it.

Is a message broker or event bus a mediator?

An event bus is closer to a publish-subscribe channel: it routes messages but usually holds no business rules. It becomes a mediator only when it decides how participants should react. In an interview, distinguish routing infrastructure from a coordinator that encodes workflow logic.

Next guide5 of 10 · Behavioral patternsMemento Pattern: Save and Restore State Without Exposing ItRead the next one