Mediator

Behavioral pattern

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.

Mediator design pattern structure
Mediator design pattern structure

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.
Mediator pattern sequence diagram
Mediator pattern sequence diagram
  1. ComponentA wants to communicate with ComponentB and sends a message through the mediator.
  2. The mediator may analyze the message for debugging or tracking purposes, or for directing it to the receiver.
  3. The message is delivered to the receiver, which in turn sends a response to the mediator.
  4. The mediator receives the response and directs it to ComponentA.
  5. Likewise, the process can go in reverse, from ComponentB to ComponentA by repeating the previous steps in order to achieve a bidirectional communication.

Real-world example

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.

Discover how the Mediator pattern can help us solve this problem
Discover how the Mediator pattern can help us solve this problem

About this book

Introduction to design patterns

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
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.