Mediator Pattern: Definition, Example, and When to Use
Mediator Pattern is a design pattern that helps objects communicate with each other through a central mediator object, reducing direct dependencies. It simplifies complex interactions by having the mediator handle all communication between components.How It Works
Imagine a group of friends trying to plan a party. Instead of everyone calling each other directly and causing confusion, they appoint one person as the organizer. This organizer listens to each friend and passes messages along, making sure everyone stays coordinated without talking to each other directly.
In software, the Mediator Pattern works the same way. Instead of objects talking directly to each other, they send messages to a mediator. The mediator then decides how to handle these messages and which objects to notify. This reduces the tangled web of connections and makes the system easier to manage and change.
Example
This example shows a simple chat room where users send messages through a mediator instead of directly to each other.
class Mediator { constructor() { this.users = []; } register(user) { this.users.push(user); user.mediator = this; } send(message, fromUser) { this.users.forEach(user => { if (user !== fromUser) { user.receive(message, fromUser); } }); } } class User { constructor(name) { this.name = name; this.mediator = null; } send(message) { console.log(`${this.name} sends: ${message}`); this.mediator.send(message, this); } receive(message, fromUser) { console.log(`${this.name} receives from ${fromUser.name}: ${message}`); } } const chatRoom = new Mediator(); const alice = new User('Alice'); const bob = new User('Bob'); const charlie = new User('Charlie'); chatRoom.register(alice); chatRoom.register(bob); chatRoom.register(charlie); alice.send('Hello everyone!'); bob.send('Hi Alice!');
When to Use
Use the Mediator Pattern when you have many objects that interact in complex ways, and direct communication between them would create a tangled mess of dependencies. It helps keep your code cleaner and easier to maintain.
Common real-world uses include user interface components coordinating actions, chat rooms managing message flow, or workflow systems where different parts need to coordinate without tight coupling.
Key Points
- The mediator centralizes communication between objects.
- It reduces direct dependencies and simplifies object interactions.
- Helps make systems easier to maintain and extend.
- Useful in complex systems with many interacting components.