Sunday, November 30, 2014

Mediator Design Pattern

Simply put, the mediator pattern is used when complex calling relationship between classes exists and we want to avoid placing the code to invoke various classes based on various considerations in all the classes involved.

Purpose

According to the GoF, the mediator pattern

Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another.

When to use this pattern?

The pattern is useful in any scenario where we want to centralize the complex relationships between multiple classes.

This pattern is extensively used for GUI programming.

Terminology

Before we go further, it makes sense to understand the terminology.

Mediator

This refers to the class that acts as the intermediate to redirect calls from one class to another.

Colleague

These are the classes that want to communicate with each other or are the actual actors in the flow.

Example

It is easier to understand this with an example. Consider a scenario where the code needs to be go through a flow. The flow contains various colleagues called in different order based on the user's input:

User Input

Sequence of call for Colleagues

1

C1 ⇒ C2 ⇒ C3

2

C2 ⇒ C4 ⇒ C3 ⇒ C6

3

C1 ⇒ C5 ⇒ C2

4

C1 ⇒ (if value < 0) { C8 ⇒ C2 } else { C6 ⇒ C3 ⇒ C7 } ⇒ C4

Pictorially

This can be represented pictorially as follows:

This would mean that the code in each of the colleagues would need to have the intelligence to call the others. This leads to a lot of duplication of code.

When a mediator is used, the code organization looks like this:

Code Snippet

The complete code is present at my github repo. The following sections show a relevant part of the code.

Advantages

Increases reusability by ensuring that each of the colleague classes adhere to some simple requirements only.

Since all complicated code is maintained at a single class, the surface area of risk is reduced.

Disadvantages

The Mediator class can become very complex. This means that any change between any unrelated use case would require all use cases to be tested. It can lead to spaghetti code in the Mediator class. But this can be handled by following clean coding practices.