design patterns ·
Mediator
Defines an object that encapsulates how a set of objects interact, reducing direct dependencies between them.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
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.
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