Mediator Design Pattern
Mediator design pattern is used for controlling the interaction between different objects.
The intent is to have an object to encapsulate the interaction of different objects.
- Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects
from referring to each other explicitly, and it lets you vary their interaction independently.
Too much communication between objects increases dependency between them, makes the system complex and reduces the reusability
of objects. Also extending the behavior requires more subclasses.
- There is too much communication between objects, which is increasing the complexity and making it difficult to reuse
There can be a separate object, which will encapsulate the behavior of interaction of the communicating objects. It will also
have responsibility for coordinating the interaction of objects. So objects will communicate through this object only.
- Encapsulate the behavior of interaction and coordination in a separate object.
Where it is applicable?
- There are set of objects with lot of interaction within them, thus increasing the dependency.
- It's becoming difficult to reuse the objects, because of too much interaction and dependency.
- Behavior has to be customizable without subclassing.
How they work together?
- Mediator class provides interface for interaction between colleague objects.
- ConcreteMediator class implements the method and does the coordination between colleague objects as required
for behavior. This has the instance of applicable colleague objects.
- Colleague class provides interface for Colleague objects. It also has the instance of Mediator object.
- ConcreteColleague class implements the method and keeps the instance of respective concrete mediator object.
- Colleague object requests mediator object for interaction with any other colleague object. Mediator object handles the
request and coordinates the communication between colleague objects as required for a particular behavior.
- So the mediator object is encapsulating the interaction, so that objects can be reused. It also reduces subclassing,
as behavior can be added or modified in mediator easily. The protocol for communication can be defined in Mediator and can
be easily modified as Mediator behaves like central controlling object for interaction.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth",
"Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article is from his courses on design patterns.