Mediator Design Pattern



What is Mediator Design Pattern ?

Mediator Design Pattern is a linkage between several components. it orchestrates how these components communicate with each other with having to coupling components to each other.

What Problems are the mediator solve ?

When a component calls another directly, that means both components are tightly coupled.

In another words, if component A has to know about component B, if one of them changed, the other component must change the code also still be able to communicate with it.

In software engineering, when a group of components call each other directly and they are tightly coupled to each other, this leads to a very bad practice in programming called "Spaghetti code" where you can't separate a component from another easily, this adds to code complexity and maintainability.

Mediator Design Pattern UML Diagram

Mediator Design Pattern UML Diagram

Each Component know how to communicate with the mediator, they notify the mediator with the message containing the new state, and the mediator is responsible for delivering the message to the other components.

Implementation of Mediator Design Pattern

The component classes implement IComponent interface which defines three main methods :

  1. Listen : Which start listening for an event from a "source" component.
  2. Receive : Receives a new state from a "source" component
  3. ChangeState : An Action method that runs after some logic

The Mediator class contains a group of listeners, each listen to a source defined by it's string value, when a source sends a message, the mediator handles it and sends it to each component that want to get this message.

The main program