Mediator
Instead of components talking directly to each other and creating a dependency web, they all talk through a Mediator — one place owns all the communication logic.
Intent & Description
🎯 Intent
Reduce the spaghetti of direct component-to-component dependencies by centralizing communication through a single mediator.
📋 Context
You have a UI with a form, several input fields, dropdowns, and buttons that all need to react to each other. Or a chat room where participants need to broadcast messages. Components are tightly coupled — changing one requires updating all the others it communicates with.
💡 Solution
Components don’t reference each other. They reference the Mediator and emit events to it. The Mediator knows who cares about what and routes accordingly. Adding a new component = register it with the Mediator, touch nothing else.
Real-world Use Case
Source
📌 TL;DR
Components talk to the Mediator, not to each other. Cuts the N×N coupling web to N×1. Watch out — the Mediator can become a God Object if you’re not careful.
Advantages
- Each component only knows about the Mediator — zero cross-component coupling.
- Add new components or change communication logic in one place.
Disadvantages
- The Mediator is a God Object waiting to happen — it absorbs complexity from all sides and can become unmaintainable.
class Mediator {
notify(sender, event) {}
}
class ConcreteMediator extends Mediator {
constructor(c1, c2) {
super();
this.c1 = c1;
this.c1.setMediator(this);
this.c2 = c2;
this.c2.setMediator(this);
}
notify(sender, event) {
if (event === 'A') {
console.log("Mediator reacts on A and triggers following operations:");
this.c2.doD();
}
}
}