Mediator Pattern in JavaScript: What It Is and How It Works
Mediator Pattern in JavaScript is a design pattern that helps objects communicate with each other through a central mediator object instead of directly. This reduces dependencies between objects and makes the code easier to manage and change.How It Works
Imagine a group of friends who want to talk but instead of calling each other directly, they all send messages through a single friend who acts as a messenger. This messenger knows who should get each message and handles the communication. In JavaScript, the mediator acts like this messenger.
Instead of objects talking directly to each other, they send messages to the mediator. The mediator then decides what to do with those messages and which objects should be informed. This way, objects don’t need to know about each other’s details, making the system simpler and easier to change.
Example
This example shows a simple chat room where users send messages through a mediator. Users don’t talk directly but use the chat room to communicate.
class ChatRoom { constructor() { this.users = {}; } register(user) { this.users[user.name] = user; user.chatRoom = this; } send(message, from, to) { if (to) { // Private message to.receive(message, from); } else { // Broadcast message for (const key in this.users) { if (this.users[key] !== from) { this.users[key].receive(message, from); } } } } } class User { constructor(name) { this.name = name; this.chatRoom = null; } send(message, to) { this.chatRoom.send(message, this, to); } receive(message, from) { console.log(`${from.name} to ${this.name}: ${message}`); } } const chatRoom = new ChatRoom(); 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!', alice); charlie.send('Hey Bob!', bob);
When to Use
Use the Mediator Pattern when you have many objects that need to communicate but you want to avoid complex direct connections between them. It helps keep your code organized and easier to maintain.
For example, in user interface programming, different UI components can communicate through a mediator to update each other without tight coupling. Another case is in chat applications where users send messages through a central chat room mediator.
Key Points
- The mediator centralizes communication between objects.
- Objects don’t need to know about each other directly.
- This reduces dependencies and simplifies code changes.
- It is useful in complex systems with many interacting parts.