The mediator design pattern simplifies the communication between objects. It does so by introducing the middleman. In other words, the mediator.
- Each object communicates only with the mediator.
- The letter contains all the logic that defines how the objects interact.
- The mediator pattern promotes loose coupling. The objects must not refer to each other directly. By removing the dependencies between the peers, we get a better, more flexible design.
- Since the objects are not connected, they can function independently. We can easily reuse or modify them as they are not tightly coupled with other types, whereas if the number of connections between objects is high, we get the monolithic system. Such systems are hard to maintain.
The mediator encapsulates how objects interact and promotes loose coupling by keeping objects from referring to each other explicitly.
Let’s look at a Chat application of an organization as an example. Our chat app has several users. The users of the org can communicate with any one in that org. Each user will have their own user-id.
To chat with each other these user must be connected with each other. When deploying the chat app we can configure each user with the list of all other users in the org. Now this works fine. But as we add new users we need to keep updating every users’ user-list. This makes it difficult to make any changes or fix potential issues. Here’s where an intermediary can help us. Instead of linking every user one by one, we introduce a middle man. All the users communicate with this mediator, and they are now totally independent without having to maintain a user list. The user when needs to communicate with another user asks the mediator to get connection. The mediator encapsulates the logic for searching for the other user and if exists connects else provides error accordingly. When new users are added to the org, the necessary logic will be added to the mediator. The mediator removed the tightly coupling between the user objects that need to communicate. So this was a practical example which demonstrates the benefits of the mediator pattern.
Another example would be Smart Home System, where multiple sensors and appliances are connected to a central hub which acts as a medaitor.
To summarize everything up the mediator promotes loose coupling. By reducing the dependencies between our types, they can be reused easily. All the objects should communicate with the mediator instead of talking to each other directly. The mediator encapsulates all the required control logic.
Disadvantage: Since the mediator contains all the control logic for the entire system, its code may become overly complex. We can prevent this with the proper design and by applying further patterns.