Design Pattern means that “we had some problem then we found the solution and gave name to this solution” and Mediator design is also one of the solution so we need to find the problem that Mediator has solved and how ?
This design pattern comes under Behavioral Category (It tells that how objects are communicating with each other (objects have been created already)).
================================================================
C++ Mediator Design Pattern :
Standard Definition:
Define an object that encapsulate how a set of object are interacting, it promotes loose coupling by keeping objects from referring to each other explicitly and it lets you vary their interaction independently.
In layman language:
Many to many communication.
Problem:
Two or more object want to communicate with each other (2 ways communication) but we don’t want tightly coupled, its very difficult to extend the communication for new object.
Definition:
Introduce the new object, all object will communicate via this new object(no direct communication).
Objective/Purpose:
Convert the tight couple communication to lose communication, make it extendable and easy to handle.
Diagram of many to many WITHOUT Mediator:
Diagram of many to many with Mediator:
When we will use mediator:
- When many to many communication is there then we can use mediator.
- When direct communication between 2 or more object is not recommendable.
Advantage:
- Loose coupling (each object is communication via mediator so we can change any time)
- Flexible (We can add new object any time without polluting existing code).
- easy to maintain, easy to manipulate, easy to extend.
- It abstract the interaction behaviour (interaction is handled in mediator object) so it can be changes without effecting individual behaviour of objects.
Disadvantage:
- It centralise the control so it can become complex object.
- If it become complex object then its hard to maintain or extend.
- If change in mediator interface then all user/object will be effected.
Key Points:
- Promote lose couple.
- Promote many to many relationship between peers.
- easy to maintain, easy to manipulate, easy to extend.
- encapsulate all interconnection and act as hub.
- Provide flexibility.
- Inside Mediator we can use observer pattern for registration and communicate with other peers.
- Inside Mediator we can use type checking, peer can pass itself to mediator and communicate with other peers
- Peers could be same type or different type.
Diagram of many to many with Mediator real example: