The Mediator pattern untangles object-to-object communication by routing everything through a central coordinator. Instead of every object knowing about every other object, they only know about the mediator.
class Mediator {
constructor() {
this.colleagues = [];
}
register(colleague) {
this.colleagues.push(colleague);
colleague.setMediator(this);
}
send(message, sender) {
this.colleagues.forEach((colleague) => {
if (colleague !== sender) {
colleague.receive(message);
}
});
}
}
class Colleague {
constructor(name) {
this.name = name;
this.mediator = null;
}
setMediator(mediator) {
this.mediator = mediator;
}
send(message) {
console.log(`${this.name} sends: ${message}`);
this.mediator.send(message, this);
}
receive(message) {
console.log(`${this.name} receives: ${message}`);
}
}-
Mediator Class:
- Constructor: Initializes an empty array
colleaguesto keep track of registered colleagues. register(colleague): Adds a colleague to thecolleaguesarray and sets the mediator for that colleague.send(message, sender): Sends a message to all colleagues except the sender. It iterates over thecolleaguesarray and calls thereceivemethod on each colleague that is not the sender.
- Constructor: Initializes an empty array
-
Colleague Class:
- Constructor(name): Initializes the colleague with a
nameand sets themediatortonull. setMediator(mediator): Sets the mediator for the colleague.send(message): Sends a message through the mediator. It logs the message being sent and calls thesendmethod on the mediator.receive(message): Logs the message received by the colleague.
- Constructor(name): Initializes the colleague with a
const mediator = new Mediator();
const colleague1 = new Colleague("Colleague1");
const colleague2 = new Colleague("Colleague2");
const colleague3 = new Colleague("Colleague3");
mediator.register(colleague1);
mediator.register(colleague2);
mediator.register(colleague3);
colleague1.send("Hello, World!");
colleague2.send("Hi there!");
colleague3.send("Good day!");- An instance of the
Mediatorclass is created. - Three instances of the
Colleagueclass are created with names "Colleague1", "Colleague2", and "Colleague3". - Each colleague is registered with the mediator using the
registermethod. - Each colleague sends a message using the
sendmethod, which is then relayed to the other colleagues by the mediator.
With 3 colleagues, direct communication would mean 6 possible connections. With 10, it's 90. The Mediator flattens that: every colleague talks to one object, and the mediator figures out who needs to hear it. Real-world examples include chat rooms, air traffic control, and UI event buses where many components need to react to each other's state.