The Mediator pattern is one of the Behavioral design patterns, which focuses on how objects communicate with each other. It defines an object that encapsulates how a set of objects interact. This pattern promotes loose coupling between interacting objects by centralizing their communication through a mediator object.
In real-world scenarios, imagine a group of people in a room who need to communicate with each other. Instead of everyone talking directly to one another, they might use a facilitator or a moderator to relay messages. The Mediator pattern works similarly by providing a centralized point for objects to interact without needing to reference each other directly.
The key components involved in the Mediator pattern are:
The benefits of using the Mediator pattern include:
Let's explore a practical example of the Mediator pattern using JavaScript. We'll create a simple chat application where multiple users can send messages to each other through a central mediator.
First, we define an interface for our colleagues. In this case, it will be a User class that holds a reference to the mediator and provides methods for sending and receiving messages.
1class User {2constructor(name, mediator) {3this.name = name;4this.mediator = mediator;5}67send(message) {8this.mediator.send(message, this);9}1011receive(message, from) {12console.log(`${from.name} to ${this.name}: ${message}`);13}14}
Next, we define the ChatMediator class that implements the mediator interface. This class will manage the interactions between users.
1class ChatMediator {2constructor() {3this.users = [];4}56addUser(user) {7this.users.push(user);8}910send(message, sender) {11this.users.forEach(user => {12if (user !== sender) {13user.receive(message, sender);14}15});16}17}
Now, let's create some users and a mediator, and add the users to the mediator.
1const mediator = new ChatMediator();23const user1 = new User('Alice', mediator);4const user2 = new User('Bob', mediator);5const user3 = new User('Charlie', mediator);67mediator.addUser(user1);8mediator.addUser(user2);9mediator.addUser(user3);
Finally, let's simulate sending messages between users.
1user1.send('Hello everyone!');2user2.send('Hi Alice!');3user3.send('Hey there!');
When you run the above code, you should see the following output:
Alice to Bob: Hello everyone! Alice to Charlie: Hello everyone! Bob to Alice: Hi Alice! Bob to Charlie: Hi Alice! Charlie to Alice: Hey there! Charlie to Bob: Hey there!
In this tutorial, we explored the Mediator pattern and how it can be used to manage interactions between objects in a decoupled manner. In the next section, we will delve into another Behavioral design pattern called the Memento Pattern, which provides a way to save and restore an object's state without exposing its internal structure.
Feel free to experiment with the Mediator pattern in your projects and see how it can simplify complex communication scenarios!