What is mediator?
A mediator is a special piece of software that sits in the middle of two or more components and handles all the communication between them, so the components don’t talk to each other directly.
Let's break it down
Imagine three friends who need to share information. Instead of each friend calling every other friend, they all send their messages to a single group leader. The leader (the mediator) receives a message from one friend and then decides which other friends should get that information. In code, the friends are objects or modules, and the group leader is the mediator object that receives calls and forwards them as needed.
Why does it matter?
When components talk directly, they become tightly linked - changing one often forces changes in the others. A mediator removes those direct links, making the system easier to understand, modify, and test. It also helps keep the overall design tidy and prevents a tangled “spaghetti” of connections.
Where is it used?
- UI frameworks (e.g., a dialog box mediating between buttons, text fields, and sliders)
- Chat or messaging apps (a server mediates messages between users)
- Event‑bus systems in micro‑service architectures
- Game engines where a central controller coordinates player actions, AI, and physics
- Any situation where many parts need to stay in sync without knowing each other’s details.
Good things about it
- Loose coupling: components don’t need to know about each other’s internals.
- Single point of control: all communication rules are in one place, making updates straightforward.
- Improved readability: the flow of data is easier to follow because it passes through the mediator.
- Easier testing: you can test components in isolation by mocking the mediator.
Not-so-good things
- The mediator can become a “god object” that knows too much, turning into a maintenance headache.
- Adding a mediator introduces an extra layer, which can slightly affect performance.
- Over‑engineering: for very small projects, a mediator may add unnecessary complexity.