Design Pattern Download: The Mediator Pattern
The Mediator pattern is a Behavioral Pattern used in software engineering when we want to reduce the amount of direct communication our systems have with each other therefore reducing the dependencies one object has on multiple others.
Example
Imagine we have a very busy airport with lots of planes, helicopters, Jets and any other flying apparatus coming into and flying out of it. However, we can only have one aircraft land at a time (because for some reason we only have one runway). So how do we coordinate amongst all the aircraft who is landing and who should wait. The solution is that we need a way for one of these aircraft to notify all the other ones when it is landing. If we have N aircraft then we need N² connections which is very messy and chaotic! Instead let’s use an air traffic tower (the mediator). Now, when an aircraft needs to land it will tell the air traffic controller who will then notify all other aircraft. This way we reduce our connections to N (connections from the aircraft to the air traffic controller).
When to use a Mediator?
- When classes are tightly coupled and rely on one another’s process and or state.
What is the Mediator composed of?
- The Components (the multiple interconnected objects i.e. our aircraft)
- The Mediator (the central point the individual components use to talk to each other)
Implementation
The Components
The Mediator
Now we can have Helicopter land and notify the air traffic controller which will tell the plane not to land yet.
Helicopter: I am landing
Plane: I am staying in the air because another vehicle is landing