Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:See book
The Mediator design pattern handles the manner in which a group of classes interact with each other. This pattern is especially useful when we have a large number of classes communicating directly with one another. By implementing this pattern, we can create a bidirectional communication layer, which can be used by a class in order to interact with others through a common object acting as a mediator.
One of the main problems we face when building large projects is that the number of classes can grow even larger and increase the interactions and relationships between them. This can bring issues with coupling, especially when we're creating direct communication channels which can be hard to track and debug.
The components included in the pattern are:
- Client:Component for starting the communication with the rest of the components through the mediator.
- Components:These are parts of the mediator communication network, that is, diverse objects sharing the same mediator for communicating with each other.
- Mediador:Component for handling the communication between the rest of the components. It directs the incoming messages to the corresponding receiver.
- ComponentA wants to communicate with ComponentB and sends a message through the mediator.
- The mediator may analyze the message for debugging or tracking purposes, or for directing it to the receiver.
- The message is delivered to the receiver, which in turn sends a response to the mediator.
- The mediator receives the response and directs it to ComponentA.
- Likewise, the process can go in reverse, from ComponentB to ComponentA by repeating the previous steps in order to achieve a bidirectional communication.
By implementing the Mediator design pattern, we are going to develop a modular application, which will have a Mediator as a central communication point for all the modules, eliminating the possibility to have a dependant relationship between them.