Easy patterns: Mediator
This article is created in continuation to series of easy patterns description and describes structural pattern for reduce coupling between two objects which interact.
Currently you can find articles for such patterns:
Creational patterns:
Structural patterns:
Behavioral patterns:
Mediator (this article)
The main essence
This pattern determines relation between two objects. Where third object is added between them to control their interaction. This reduces coupling between these objects and they don’t have to know implementation details of each other.
Example of use
This example describes users communication through messenger. Each user can sendMessage
which delegates posting message to mediator
instance. So, users don’t know about implementation of each other, but have access to messenger instance which handles everything they are interested in.
Profit
Systems with a high level of coupling can have a lot of problems potentially. This pattern helps to reduce coupling level, so components have more flexibility in their interaction.
Adding mediator component leads to concern separation: all logic related to interaction is placed in one module, so it’s easy to debug it if something goes in wrong way. No implementation details needed from each object that needs to communicate with others.
Weak places
Adding mediator as extra layer leads to slight performance reduce. It’s hard to predict reaction of the system basing only on events which happening inside it, but generally it’s usual price for reducing coupling.
Conclusion
If you found this article helpful, please hit the 👏 button and feel free to comment below!