Software

Mediator Pattern

Imagine the next situation, you have the smart home where devices communicate to each other and do one or another action dependent on the state of another device.

No Mediator Visualization Diagram.png

The visualization looks complicated and will be even more complicated if needed additional connections between the devices. To simplify the design, must to implement the Mediator pattern, this is how it should looks:

Mediator Visualization Diagram.png

In the Mediator pattern, you will add an object that will talk to all of these other objects and coordinate their activities.

The communication between an object and the mediator is two-way: the object informs the mediator when something happens. For example, your Phone object could inform the mediator when your alarm goes off.

The mediator can perform logic on these events. For example, the mediator could track the number of times the alarm has gone off.

Finally, the mediator can request information or behavior from an object. If the alarm has gone off three times, then the mediator could ask your door to open, which would allow your dog to go in and jump on you to help wake you up.

Mediator Class Diagram.png

The objects associated with your mediator are called colleagues. You define an interface for the interactions between the mediator and colleagues, then instantiate a concrete mediator and concrete colleagues as necessary.

The communication could be implemented as an Observer pattern. Each Colleague is a subclass of the Observable class, and the Mediator is an Observer to each of them. In this case, the colleague should pass itself as a parameter to the mediator, so that the mediator knows to check that colleague instead of checking all of them. The communication could also occur through an event infrastructure.

A common usage for the mediator pattern, identified by the Gang of Four, is for dialog boxes with many components. As the user makes selections, such as checking a box or choosing a certain bullet out of a list, other parts of the dialog may have to be grayed out or changed in some other way. Instead of components talking to each other directly, a mediator can easily manage the different interactions like this.

The Mediator allows for loose coupling between colleagues. Since each of these colleagues only communicates with the mediator, they can be reused more easily. Centralizing the logic of interaction between all of these related objects in one central object makes for code that is easier to read, maintain, and extend.

On the other hand, the mediator can quickly become very large. Large classes are generally discouraged because they make code more difficult to debug. The benefits of centralization should be balanced against the downsides of a large, difficult-to-read mediator class.

One thought on “Mediator Pattern

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.