Design Patterns
Mediator
Sending one message through the mediator adds O(1) extra work (a constant amount) before it does its own job.
The idea, in plain English
A mediator works like an air-traffic controller. Planes don't radio each other directly to sort out who lands first — that would be chaos with dozens of planes. Instead, every plane talks only to the control tower, and the tower coordinates everyone. In code, a mediator object sits in the middle, so objects talk through it instead of directly to each other.
How it works
- 1You give every object a reference to one shared mediator, instead of references to each other.
- 2When an object wants to 'talk', it sends its message to the mediator, not directly to another object.
- 3The mediator decides what to do with the message — like passing it along to everyone else who needs it.
When you'd use it
Use this when many objects need to coordinate, but wiring them all directly to each other would turn into a tangled mess. Examples: chat rooms, UI widgets that react to each other, or air traffic control.
Common beginner mistakes
- Don't let objects quietly keep direct references to each other 'just in case'. That brings back the tangled mess the mediator was meant to avoid.
- Don't let the mediator grow so many responsibilities that it becomes an unmanageable giant class.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Alice: Hi Bob!
Bob: Hey Alice!Not sure this is the right topic? See the learning paths → or where this leads →