As stated in GoF, p273 :
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from refereing to each other explicitly, an it lets you vary their interaction independently.
In other words, make mediation between various items an independent concept by introducing an object that deals with it.
Participants
- Mediator : Interface for communicating with Colleague objects.
- ConcreteMediator: Implements Mediator interface by coordinating Colleague objects. Knows and maintains Colleagues.
- Colleagues classes :
- Each instance has a reference to its Mediator object (or knows about it in some way).
- Communicates with other Colleague using Mediator only.
How to implement
- Identify a collection of objects that would benefit from mutual decoupling.
- Encapsulate those interactions in the abstraction of the Mediator.
- Create your Mediator and rework all "peer" objects to interact with it only.
- Be careful not to create a God object.
Note : UML class diagram taken from here
Pros
- Decouples colleagues : Promotes loose coupling between colleagues.
- Abstracts how objects interact
- Centralizes control
- Simplify objects protocol (from many to many to many to one.)
Cons
- The complexity that previously was in the interaction between objects is now in the Mediator. This can produce a complex object.
Here are some usefull ressources :
- w3sdesign
- A Refactoring guru article.
