Mediator
Category
Behavioral pattern
Problem
Reduce coupling between classes that communicate with each other by making them communicate indirectly through a mediator object. Without a mediator, classes have direct references to each other (spaghetti coupling).
Solution
- Create a Mediator object that encapsulates how a set of objects interact
- Colleague classes communicate with each other only through the mediator
- The mediator coordinates the interaction and knows about all colleagues
Structure
- Mediator: Interface for communicating with colleague objects
- ConcreteMediator: Implements mediator; knows and coordinates colleagues
- Colleague: Interface for colleague objects
- ConcreteColleague: Communicates with other colleagues through the mediator
Key Benefits
- Reduced coupling — Colleagues don’t need to know about each other
- Centralized control — Interaction logic is centralized in the mediator
- Simplified colleagues — Colleagues are simpler because they don’t manage complex relationships
Trade-offs
- Mediator becomes complex — The mediator can become a god object managing all interactions
- Indirection — Harder to understand the flow of control
When to Use
- A set of objects communicate in well-defined but complex patterns
- Reusing an object is difficult because it communicates with many others
- You want to customize a pattern distributed among many classes