Mediator
17 Mar 2022Intent
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.
Applicability
Use the Mediator pattern when:
- A set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.
- Reusing an object is difficult because it refers to and communicates with many other objects.
- A behavior that's ditributed between several classes should be customizable without a lot of subclassing.
Structure
Participants
- Mediator: defines an interface for communicating with Colleague objects.
- ConcreteMediator: implements cooperative behavior by coordinating Colleague objects, knows and maintains the colleagues.
- Colleague classes: each Colleague class knows it's mediator object, each colleague communicates with the mediator whenever it would have otherwise communicated with another colleague.
Collaborations
Collagues send and receive requests from a Mediator object. The mediator implements the cooperative behaviour by routing requests between the appropriate colleagues.
Consequences
The mediator pattern has the following benefits/consequences:
- It limits subclassing: a mediator localizes behaviour that otherwise would be distributed among several objects.
- It decouples colleagues.
- It simplifies object protocols.
- It abstracts how objects cooperate.
- It centralizes control.
Sample Code
Related Patterns
- Facade differs from Mediator in that it abstracts a subsystem of objects. Mediator enables cooperative behavior that colleague objects don't or can't provide.
- Colleagues can communicate with the mediator using the Observer pattern.