Mediator Pattern
Reduce chaotic dependencies between objects by restricting direct communications between the objects and forcing them to collaborate only via a mediator object.
Intent & Objective
Facilitate loose coupling between a set of interacting components by keeping them from referring to each other explicitly, centralizing interactions in a single mediator.
"Instead of the bride and groom coordinating directly with caterers, florists, DJs, and photographers, the planner acts as the central coordinator."
"Mediates disputes between students and communicates with school administration so students don’t directly petition the principal."
"Connects buyers, sellers, home inspectors, and escrow officers without direct adversarial friction."
"The Scrum Master coordinates communication between developers, testers, and product owners to align sprint goals."
The Problem
Spiderweb coupling: every component has direct references to 10 other components, making changing or testing any single component nearly impossible.
The Solution
Extract all relationships between components into a separate mediator class. Components know only about their mediator.
Key Participants & Architectural Roles
Code Samples (Traditional OOP vs Functional Programming)
Available in C++, Python, and JavaParadigm Contrast: Traditional OOP vs Functional / Data-Oriented
In OOP, Mediator is a central coordinator object. In Functional Programming, Mediator is an Event Bus, Message Broker channel, or Elm/Redux architecture where all components emit actions to a centralized dispatcher.
Advantages
- ✓ Single Responsibility Principle: extracts communications between various components into a single place
- ✓ Open/Closed Principle: introduces new mediators without having to change the actual components
- ✓ Eliminates chaotic many-to-many dependencies
Trade-offs
- ✗ Over time a mediator can evolve into a God Object
When to Apply
- → When it’s hard to change some of the classes because they are tightly coupled to a dozen other classes
- → Complex UI forms where changing a checkbox enables/disables 5 other fields and recalculates buttons
When to Avoid
- ! When objects have simple, linear relationships