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.
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
dropAtanddevelopAtlive 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: onfrom __future__ import annotations
from typing import Literal, Optional, Protocol
RoastEvent = Literal["temperature", "doorOpened"]
class RoastMediator(Protocol):
def notify(self, sender: Component, event: RoastEvent) -> None: ...
class Component:
def __init__(self) -> None:
self.mediator: Optional[RoastMediator] = None
def set_mediator(self, mediator: RoastMediator) -> None:
self.mediator = mediator
class TemperatureProbe(Component):
def __init__(self) -> None:
super().__init__()
self.last_reading = 0
def read(self, celsius: int) -> None:
self.last_reading = celsius
print(f"probe: {celsius}C")
if self.mediator:
self.mediator.notify(self, "temperature")
class Burner(Component):
def __init__(self) -> None:
super().__init__()
self.level = 100
def set_level(self, percent: int) -> None:
self.level = percent
print(f"burner: level {percent}%")
def off(self) -> None:
self.set_level(0)
class DrumDoor(Component):
def __init__(self) -> None:
super().__init__()
self.is_open = False
def open(self) -> None:
if self.is_open:
return
self.is_open = True
print("door: open")
if self.mediator:
self.mediator.notify(self, "doorOpened")
class CoolingFan(Component):
def __init__(self) -> None:
super().__init__()
self.running = False
def start(self) -> None:
self.running = True
print("fan: on")
class RoastController:
def __init__(
self,
probe: TemperatureProbe,
burner: Burner,
door: DrumDoor,
fan: CoolingFan,
drop_at: int = 210,
develop_at: int = 190,
) -> None:
self.probe = probe
self.burner = burner
self.door = door
self.fan = fan
self.drop_at = drop_at
self.develop_at = develop_at
for part in (probe, burner, door, fan):
part.set_mediator(self)
def notify(self, sender: Component, event: RoastEvent) -> None:
if sender is self.probe and event == "temperature":
self._on_temperature(self.probe.last_reading)
elif sender is self.door and event == "doorOpened":
self.fan.start()
def _on_temperature(self, celsius: int) -> None:
if celsius >= self.drop_at:
self.burner.off()
self.door.open()
elif celsius >= self.develop_at and self.burner.level > 40:
self.burner.set_level(40)
if __name__ == "__main__":
probe = TemperatureProbe()
RoastController(probe, Burner(), DrumDoor(), 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<?php
declare(strict_types=1);
interface RoastMediator
{
public function notify(Component $sender, string $event): void;
}
abstract class Component
{
protected ?RoastMediator $mediator = null;
public function setMediator(RoastMediator $mediator): void
{
$this->mediator = $mediator;
}
}
class TemperatureProbe extends Component
{
public int $lastReading = 0;
public function read(int $celsius): void
{
$this->lastReading = $celsius;
echo "probe: {$celsius}C\n";
$this->mediator?->notify($this, 'temperature');
}
}
class Burner extends Component
{
public int $level = 100;
public function setLevel(int $percent): void
{
$this->level = $percent;
echo "burner: level {$percent}%\n";
}
public function off(): void
{
$this->setLevel(0);
}
}
class DrumDoor extends Component
{
public bool $isOpen = false;
public function open(): void
{
if ($this->isOpen) {
return;
}
$this->isOpen = true;
echo "door: open\n";
$this->mediator?->notify($this, 'doorOpened');
}
}
class CoolingFan extends Component
{
public bool $running = false;
public function start(): void
{
$this->running = true;
echo "fan: on\n";
}
}
class RoastController implements RoastMediator
{
public function __construct(
private TemperatureProbe $probe,
private Burner $burner,
private DrumDoor $door,
private CoolingFan $fan,
private int $dropAt = 210,
private int $developAt = 190,
) {
foreach ([$probe, $burner, $door, $fan] as $part) {
$part->setMediator($this);
}
}
public function notify(Component $sender, string $event): void
{
if ($sender === $this->probe && $event === 'temperature') {
$this->onTemperature($this->probe->lastReading);
} elseif ($sender === $this->door && $event === 'doorOpened') {
$this->fan->start();
}
}
private function onTemperature(int $celsius): void
{
if ($celsius >= $this->dropAt) {
$this->burner->off();
$this->door->open();
} elseif ($celsius >= $this->developAt && $this->burner->level > 40) {
$this->burner->setLevel(40);
}
}
}
$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: onWhen 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.
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.
Define a mediator interface with a notification method, usually
notify(sender, event). Keep it small so components stay unaware of the concrete coordinator.Give components a reference to the mediator interface, typically through a base class with
setMediator, and remove their direct references to each other.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.Implement the concrete mediator: hold references to the components, and in
notifybranch on sender and event to command the right components.Let the client create the components, then the mediator, and wire them. Move configuration that describes coordination, such as thresholds, into the mediator.
Write tests for the mediator with simple fake components, and tests for each component with a fake mediator that records notifications.
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.
- Observer Pattern: Notify Subscribers Without Coupling to Them
Observer lets subscribers come and go dynamically and does not centralise the rules. A mediator often uses Observer-style notifications internally, but it adds a coordinator that knows the participants and decides what each reaction should be.
- Facade Pattern: One Simple Entry Point to a Messy Subsystem
A facade simplifies access to a subsystem for outside callers, and the subsystem classes do not know it exists. A mediator coordinates peers that do know about it and report to it.
- Chain of Responsibility: Pass a Request Along Until One Handles It
Chain of Responsibility passes a request along a sequence of handlers until one takes it. Mediator sends every message to one place that decides who reacts, so the routing is explicit rather than emergent.
- Command Pattern: Turn Requests into Objects You Can Queue and Undo
Command turns a request into an object. A mediator can issue commands to components, or components can send command objects to the mediator instead of string events.
- Inappropriate Intimacy: Classes That Know Too Much About Each Other
Components that reach into each other's state and methods are a sign that a mediator could own their interaction instead.
- Large Class
The main risk of this pattern: if your mediator accumulates unrelated rules, split it before it becomes the class everyone is afraid to edit.
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.