Mediator

GoF Definition

Define an object that encapsulates how a set of objects interact. Mediator promotes

loose coupling by keeping objects from referring to each other explicitly, and it lets you

vary their interaction independently

A system consisting of several different types of objects often needs a way for those objects to communicate with each other. If every interested object is supposed to communicate with the other objects directly, it can lead to complications and tight coupling.

Mediator takes responsibility for controlling and coordinating the interactions of a specific group of objects that cannot refer each other explicitly. In other words, a mediator is an intermediary through whom these objects talk to each other. The mediator pattern defines a way for objects to interact with each other through a central coordinating object.

This kind of implementation helps you to reduce the number of interconnections among different objects. As a result, you can reduce the coupling in the system because sender and receiver objects don’t need to know anything about each other, they can be modified independently without affecting each other.

One real world use of this pattern is:

Chat service, messaging services (Rabbitmq) and ESB.

In chat service, all messages go through a mediator.

Example: This is real life example of mediator is beneficial. Here air traffic controller station acts as mediator.

Check list

  • Identify a collection of interacting objects that would benefit from mutual decoupling.

  • Encapsulate those interactions in the abstraction of a new class.

  • Create an instance of that new class and rework all "peer" objects to interact with the Mediator only.

  • Balance the principle of decoupling with the principle of distributing responsibility evenly.