Mediator Pattern
You'll learn: how the Mediator pattern centralizes complex communication between objects to reduce coupling and simplify interactions.
What Problem Does It Solve?
Imagine a busy airport control tower. Without it, every airplane would need to communicate directly with every other airplane to coordinate takeoffs, landings, and taxiing—a chaotic mess of interconnected dependencies. The control tower acts as a mediator, centralizing all communication so planes only talk to the tower, never to each other.
In software, when multiple objects need to interact, direct connections between them create tight coupling. If Object A talks to B, C, and D, and they all talk back, you get a web of dependencies that's hard to maintain and modify.
How the Mediator Pattern Works
The Mediator pattern introduces a single mediator object that encapsulates how a set of objects (colleagues) interact. Instead of objects referring to each other directly, they communicate through the mediator. This promotes loose coupling—colleagues don't need to know about each other, only about the mediator.
Structure:
- Mediator interface: defines how colleagues communicate
- Concrete Mediator: implements coordination logic
- Colleague objects: interact through the mediator, not directly with each other
When to Use It
Use the Mediator pattern when:
- A set of objects communicate in complex, well-defined ways
- Reusing objects is difficult because they refer to many others
- Customizing distributed behavior requires subclassing too many classes
The pattern trades complexity in colleague relationships for complexity in the mediator itself—the mediator becomes the place where interaction logic lives.
Key Takeaway: The Mediator pattern centralizes object interactions in a single mediator, preventing direct references between colleagues and making the system easier to understand and modify.