Notes
The problem
Here is the naive design. The seat picker holds the price label, the pay button and the coupon field, and calls each of them. The snack picker also holds the price label. The coupon field needs the seat count. With five parts, there can be up to twenty one-way links. Add a gift card field and you touch almost every class. None of these widgets can be reused on another screen, because each one drags its neighbours along.
Look inside the old seat picker. It knows the seat price, it decides when the pay button is enabled, and it knows that a group coupon needs two seats. Those are checkout rules, not seat picking rules. The same rules are also spread over the snack picker and the coupon field. To answer a simple question, when is the pay button on, you must read three classes.
class OldSeatPicker {
OldPriceLabel price;
OldPayButton pay;
OldCouponField coupon;
void select(int n) {
price.show(n * 250);
pay.setEnabled(n > 0);
if (n < 2) coupon.clear();
}
} The idea
The idea: objects stop talking to each other. Each one only tells a mediator that something changed in it. The mediator holds the rules about how the parts work together, and tells the others what to do. The tangle becomes a star. Five widgets now need five links to the centre instead of up to twenty links between them, and every interaction rule lives in one class.
- objects do not talk to each
- other directly
- each one tells a mediator
- "something changed in me"
- the mediator holds the rules
- and tells the others what
- to do
- many to many becomes one to many
Participants
The participants with our names. Checkout mediator is the interface, with one method: changed. Ticket checkout is the concrete mediator, which knows every widget and holds the rules. Widget is the abstract colleague: it keeps a reference to the mediator interface. Seat picker, snack picker, coupon field, price label and pay button are the concrete colleagues. Notice that a colleague only knows the interface, never the other colleagues.
A colleague
Here is a colleague. Widget holds the mediator and offers one helper, changed, which passes itself to the mediator. Seat picker stores the new seat count and calls changed. That is all. It does not know a price exists, or a coupon, or a pay button. You could drop this seat picker into a concert booking screen with a different mediator and it would just work.
abstract class Widget {
private final CheckoutMediator mediator;
protected final void changed() {
mediator.changed(this); }
}
final class SeatPicker extends Widget {
private int seats;
void select(int count) {
seats = count;
changed(); // tell the mediator
} } The mediator
Here is the mediator. Changed receives the widget that spoke. If it was the pay button, it books the tickets. Otherwise it checks the coupon rule: a group coupon needs at least two seats, so it rejects the coupon if not. Then it computes the total from seats, snack combos and the discount, updates the price label and switches the pay button on only when at least one seat is chosen. Every rule is in one readable place.
public void changed(Widget source) {
if (source == pay) { book(); return; }
if (groupCoupon() && seats.seats() < 2)
coupon.reject("needs 2+ seats");
int total = seats.seats() * SEAT
+ snacks.combos() * COMBO
- discount();
price.show(total);
pay.setEnabled(seats.seats() > 0);
} One run
Follow one change. The user had two seats, one snack combo and the group coupon, friends one hundred. They drop to one seat. The seat picker tells the mediator. The mediator sees the group coupon no longer applies and rejects it, so the coupon field shows a message. It recomputes the total, two hundred and fifty for the seat plus one hundred and eighty for the combo, four hundred and thirty, and keeps the pay button on.
Both directions
Traffic flows both ways. When the pay button is clicked, it reports to the mediator like any other widget. The mediator reads the seat count and the snack count, books the order and tells the pay button it is done. The pay button never asked the seat picker anything. Colleagues report upwards, and the mediator reads from them and gives commands downwards.
What you gain
What do you gain? Colleagues become small and reusable, because they no longer know their neighbours. The interaction rules are in one class, so you can read them and change them in one place. Adding a gift card field means one new colleague and a few lines in the mediator. And you can test the rules by driving fake widgets, with no real screen at all.
- colleagues are small and
- reusable on other screens
- interaction rules are in
- one class, easy to read
- add a widget: change the
- mediator, not five classes
- test the rules with fake
- widgets, no real screen
- links: n instead of n x n
The god mediator
The big risk is a god mediator. The complexity does not vanish, it moves into the middle, and it can grow into a two thousand line class that knows everything. Keep it lean. Use one mediator per feature or per section of the screen. Keep logic that belongs to one widget inside that widget. And let the mediator coordinate, while real calculations, like pricing, live in their own classes that it calls.
- risk: every rule of the
- whole screen in one class
- fixes:
- one mediator per feature
- or per screen section
- keep widget logic inside
- the widget
- mediator only coordinates,
- it does not compute prices
When to use it
Use a mediator when several objects react to each other in many-to-many ways, when you want to reuse those objects elsewhere, or when the rules between them change often. Skip it when only two or three objects talk, or when the flow is one way. A direct call or a simple listener is clearer there. Adding a coordinator between two objects is just extra indirection.
- use it when:
- many objects react to each
- other in tangled ways
- you want to reuse the parts
- rules change often
- skip it when:
- only two or three objects
- the flow is one-way: use
- Observer or a direct call
Neighbours
Compare it with its neighbours. In Observer, a subject broadcasts an event and does not care what the listeners do. It is one to many and one way. A facade is a simple front door for outside callers, and the classes behind it never call the facade. A mediator sits among peers: they talk to it and it talks back, and it owns the rules between them. In practice a mediator often uses observer style events to hear from colleagues.
- Observer: subject broadcasts,
- does not know what listeners
- do; one-to-many, one way
- Facade: a simple front door
- for outside callers; the
- subsystem never calls it
- Mediator: colleagues talk
- both ways with it, and it
- holds the rules between them
In practice
The Java standard library has no class called mediator, but the shape is everywhere. A screen controller that wires form widgets together is a mediator. So is an MVC controller sitting between the view and the model, or a match manager in a game between players and the board. At system scale, a message broker or a workflow orchestrator plays the same role between services, so they do not call each other directly.
- UI: a screen controller that
- wires form widgets together
- MVC: the controller between
- view and model
- games: a match manager
- between players and board
- systems: a message broker or
- workflow orchestrator
- between services
In LLD interviews
In interviews, look for many peers that must coordinate through one place. In an elevator system, a dispatcher sits between floor buttons and elevator cars, so cars never talk to each other. A group chat room relays messages between users. A control tower assigns runways to planes. An auctioneer stands between bidders. When you draw the dispatcher, say it is a mediator, and say how you keep it from becoming a god class.
- elevator: dispatcher between
- floor buttons and cars
- group chat: room relays
- messages between users
- airport: a control tower
- assigns runways
- auction: auctioneer between
- bidders
- smart home hub
Common mistakes
Common mistakes. Event loops: the mediator updates the coupon field, the coupon field fires changed again, and the two call each other forever. Commands from the mediator should not trigger new events. Colleagues that still keep references to each other, so the tangle quietly returns. One global mediator for the whole app. And business logic inside the mediator that belongs in model classes.
- mediator updates a widget,
- widget fires changed()
- again: endless loop
- colleagues still hold refs
- to each other
- one global mediator for
- the whole app
- business logic inside the
- mediator instead of models