Design patterns – Mediator

When faced with multiple classes that communicate with each other, we have the problem of maintaining the code. Mediator is a pattern that decouples the dependency between those classes.

The mediator should only be a dispatcher, and should not interfere between the sender and the receiver. Instead of the classes talking with each other, they talk through a mediator.

This implies that all the classes that want to communicate, should have a way to access the mediator (mediator being a singleton, or the classes containing a reference to it).

Let’s say we have class1, class2, class3, class4 and they communicate with each other like this:

etc..that’s a mess! And what if we need to keep track whether they can execute that function? Maybe they need to know what happens with the other classes as well. Or what if other classes change their function skeleton ? we need to update everywhere.

We will end up having multiple references one way to another.

Mediator solves many of the problems by putting itself in the middle, knowing which objects should take part in the conversation, and dispatching the messages from one class to another.

The full code can be found at the following link:


You may also like...

Leave a Reply