design patterns · behavioral
Mediator
Defines an object that encapsulates how a set of objects interact, reducing direct dependencies between them.
Pattern
Overview
Intent
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly.
Real-World Analogy
Air traffic control - planes do not communicate directly with each other. All communication goes through ATC (the mediator).
When many objects need to interact with many others, the O(n²) coupling creates a maintenance nightmare. Mediator introduces a central hub - objects communicate only with the mediator, which routes messages.
Each Colleague has a reference to the Mediator. When a colleague wants to communicate, it calls the mediator. The mediator decides who else needs to be notified and forwards the message.
When to use
Chat rooms, air traffic control, event buses, UI form coordination (fields enabling/disabling each other based on others), MVC controllers, microservice orchestration.
When not to
When only 2-3 objects interact - direct references are simpler. When the mediator becomes overloaded with business logic.
Participants
Key Insights
- Mediator reduces N×N connections to N connections - hub-and-spoke vs mesh topology
- Unlike Observer (one-to-many), Mediator is many-to-many with centralized routing
- React Flux/Redux store is a Mediator - components dispatch actions, store mediates state changes
- The key risk: mediator becomes a monolithic controller with all business logic