Mediator Pattern
Source:: Software Design Patterns - Best Practices for Software Developers
A mediator is defined as a person who makes people involved in a conflict come to an agreement.
Definition
The pattern is defined as encouraging loose coupling among interacting objects by encapsulating their interactions in a mediator object, thus avoiding the need for individual objects to refer to each other directly and allowing to vary object interactions independently.
It allows us to expose a unified interface through which the different parts of a system may communicate. The Mediator promotes loose coupling by ensuring that instead of modules referring to each other explicitly, their interaction is handled through this central point. 1
# Tradeoffs
- [u] Broadcasted events can be handled by any number of modules at once.
- [u] Can be used for a number of other purposes such as permission management.
- [d] Single Point of Failure
- [d] Placing a Mediator between modules can also cause a performance hit as they are always communicating indirectly.
- [d] It’s difficult to establish how a system might react by only looking at the broadcasts.
# Mediator vs Observer Pattern
1994 Design Patterns Elements of Reusable Object-Oriented Software
“In the Observer pattern, there is no single object that encapsulates a constraint. Instead, the Observer and the Subject must cooperate to maintain the constraint. Communication patterns are determined by the way observers and subjects are interconnected: a single subject usually has many observers, and sometimes the observer of one subject is a subject of another observer.”
# Mediator vs Facade Pattern
The Mediator centralizes communication between modules where it’s explicitly referenced by these modules. In a sense this is multidirectional. The Facade however just defines a simpler interface to a module or system but doesn’t add any additional functionality. Other modules in the system aren’t directly aware of the concept of a facade and could be considered unidirectional.