3.5 Mediator
The Mediator pattern uses a mediator object to encapsulate how a set of objects interact. Objects that used to reference and call each other directly now talk only to the mediator. This collapses "many-to-many" mesh coupling into a "many-to-one" star.
Picture a chatroom: if every user held references to all other users, N people means N×N connections. Introduce a chatroom mediator and each user knows only the chatroom. The lab below lets you pick a sender and watch the mediator relay the message to everyone else.
Centralize the interaction logic
interface Mediator { void notify(Component sender, String event); }
class Dialog implements Mediator {
public void notify(Component sender, String event) {
if (sender == checkbox && event.equals("toggle")) {
textField.setEnabled(checkbox.isChecked()); // coordination lives here
submit.setEnabled(/* ... */);
}
}
}Each widget no longer operates other widgets directly; it notifies the mediator "I changed," and the mediator decides who is enabled, who is disabled, who refreshes. In the form lab below, you must accept the terms to type a nickname, and type a nickname to submit — all coordinated by the mediator.
Mediator vs Facade vs Observer
- vs Facade: a facade is one-directional (client → subsystem), and the subsystem doesn't know the facade exists; a mediator is bidirectional, with colleagues actively notifying it.
- vs Observer: Observer is one-to-many one-way broadcast; a mediator coordinates multi-party bidirectional interaction with more centralized logic.
Don't let the mediator become a God Object
The mediator's biggest risk: all interaction logic gets stuffed into it until it swells into an omniscient, unmaintainable "God Object." When a mediator starts bloating, consider splitting it into several mediators by subdomain, or rethink whether these objects really need to interact so often.