November 26, 202611 minutes
A signup button's enable rule lives in four widgets, and one of them forgot the checkbox. Learn how a Mediator turns twenty links between five widgets into five, and how to keep the hub from becoming a god object.
Your signup form has five widgets: an email field, two password fields, a terms checkbox and a submit button. The button should light up only when everything is right. Last week a user signed up without ticking the terms. The rule that enables the button lives in four places, and one of them forgot the checkbox. Every widget talks straight to the others, so each one has to know the other four. How do you stop widgets from managing each other? There’s a pattern for this, and it’s called Mediator.
Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.
Five widgets, each holding the other four, is twenty links. Every one of them is a place where a rule can be copied, forgotten or contradicted.
Picture a restaurant kitchen at the dinner rush: a grill, a fryer, a salad station and dessert. Every plate for table twelve needs all four. With nobody in charge, the grill shouts at the fryer: drop the fries, my steak is almost done. The salad station shouts at dessert. Everyone has to know everyone.
So restaurants put an expediter at the pass. The stations stop shouting at each other. They tell the expediter: steak is up. And the expediter calls: fire the fries. Add a soup station and it only has to learn one person. The others don’t change. But now the expediter knows the whole kitchen.
In code, the stations are colleagues and the expediter is the mediator.
Start with two widgets. The checkbox should enable the submit button, so it holds a reference to the button.
public class Checkbox {
private final Button submit;
private boolean checked;
public Checkbox(Button submit) { this.submit = submit; }
public void toggle() {
checked = !checked;
submit.setEnabled(checked);
}
}When the box is ticked, it flips its own state and tells the button directly. Two classes, one arrow, and you can read it at a glance. That’s a fair design. For two widgets, don’t add anything.
Now the form grows. The button needs a valid email and matching passwords, so the checkbox needs the email field and both password fields too.
public class Checkbox {
private final TextField email;
private final TextField password;
private final TextField confirm;
private final Button submit;
private boolean checked;
// the constructor takes all four of them
public void toggle() {
checked = !checked;
submit.setEnabled(checked
&& email.text().contains("@")
&& password.text().equals(confirm.text()));
}
}The email field needs the button too, and so does each password field. Five widgets, each holding the other four: 5 × 4 = 20 links. The rule for enabling the button is now copied into every widget. Change it once, and you change it four times. Miss one, and you get last week’s bug.
Add a sixth widget, a newsletter box, and every other widget changes. And you can’t reuse the text field on a login screen, because it drags the signup button along. It’s a kitchen where every cook shouts at every other cook, and it works until the rush starts.
Look at what each widget really needs to say. The checkbox only needs to say: I changed. It doesn’t need to know who cares. So give the widgets one thing to talk to: the mediator. A widget reports a change to it, and that’s all it knows.
The rule moves out of the widgets into one place. The mediator hears every change, looks at the whole form, and decides what each widget should do. Twenty links become five.
The Gang of Four put it this way (Design Patterns, 1994): the intent is to “define an object that encapsulates how a set of objects interact”, and the mediator “replaces many-to-many interactions with one-to-many interactions between the mediator and its colleagues.”
Talk to the hub, not to each other.
Here are the pieces. The Mediator interface has one method, changed, and it says which widget
changed. Every Widget keeps a mediator, handed in when it’s built.
public interface Mediator {
void changed(Widget source);
}
public abstract class Widget {
protected final Mediator mediator;
protected Widget(Mediator mediator) { this.mediator = mediator; }
}A text field stores its text. When the text changes, it tells the mediator and passes itself. The checkbox does the same when it’s toggled.
public class TextField extends Widget {
private String text = "";
public TextField(Mediator mediator) { super(mediator); }
public void type(String text) {
this.text = text;
mediator.changed(this);
}
public String text() { return text; }
}
public class Checkbox extends Widget {
private boolean checked;
public Checkbox(Mediator mediator) { super(mediator); }
public void toggle() {
checked = !checked;
mediator.changed(this);
}
public boolean isChecked() { return checked; }
}Now the signup dialog is the mediator. It creates the widgets, handing each one itself, and the rule lives in a single method: is the email valid, do the passwords match, is the box ticked? Then the button is enabled. The widgets don’t know any of that.
public class SignupDialog implements Mediator {
private final TextField email = new TextField(this);
private final TextField password = new TextField(this);
private final TextField confirm = new TextField(this);
private final Checkbox terms = new Checkbox(this);
private final Button submit = new Button(this);
@Override
public void changed(Widget source) {
boolean emailOk = email.text().contains("@");
boolean passwordsMatch = password.text().equals(confirm.text());
submit.setEnabled(emailOk && passwordsMatch && terms.isChecked());
}
}A note on
this. Passingthisfrom a field initializer is legal Java and keeps the example short, but it hands out the dialog before its constructor has finished. It works here because the widgets only store the reference. In production code you would usually create the widgets in the constructor body, or give the mediator aregister(widget)method.
Follow one click. The user ticks the box. The checkbox calls changed. The dialog reads every widget
and enables the button.
Add a hint label that says passwords differ, and it’s one new field and one new line in the dialog. No widget changes.
private final Label hint = new Label(this);
@Override
public void changed(Widget source) {
boolean emailOk = email.text().contains("@");
boolean passwordsMatch = password.text().equals(confirm.text());
hint.setText(passwordsMatch ? "" : "Passwords differ");
submit.setEnabled(emailOk && passwordsMatch && terms.isChecked());
}And the text field is free to move. A login dialog is a different mediator, with the same text fields and its own rule.
public class LoginDialog implements Mediator {
private final TextField user = new TextField(this);
private final TextField pass = new TextField(this);
private final Button login = new Button(this);
@Override
public void changed(Widget source) {
login.setEnabled(!user.text().isBlank() && !pass.text().isBlank());
}
}Three roles. The Mediator interface. The ConcreteMediator, here the signup dialog, which knows its colleagues and runs the teamwork. And the Colleagues, which each know their mediator.
Notice the two directions. Colleagues know only the interface: they report. The dialog knows its colleagues by their real types, because it has to tell them what to do: it commands.
Two design choices are worth knowing:
Now the price. The mediator collects every rule. Add widgets and changed grows. Add features and it
grows more.
@Override
public void changed(Widget source) {
// validation rules for fourteen fields
// enable and disable rules for nine buttons
// show and hide rules for six panels
// analytics events, focus handling, formatting ...
// ... and four hundred lines more
}The Gang of Four say the pattern trades complexity of interaction for complexity in the mediator, and that it can become a monolith that’s hard to maintain. refactoring.guru warns that “over time a mediator can evolve into a God Object”. That’s the Large Class smell in a new costume.
Three habits keep it small:
@Override
public void changed(Widget source) {
boolean emailOk = email.isValid(); // the rule moved into the field
boolean passwordsMatch = password.matches(confirm); // so did this one
submit.setEnabled(emailOk && passwordsMatch && terms.isChecked());
}For that to compile, TextField gains two small methods:
// added to TextField
public boolean isValid() { return text.contains("@"); }
public boolean matches(TextField other) { return text.equals(other.text); }ButtonGroupSwing has a small one. A size menu with three radio buttons: small, medium, large. Choosing one has to clear the other two.
JRadioButton small = new JRadioButton("Small");
JRadioButton medium = new JRadioButton("Medium");
JRadioButton large = new JRadioButton("Large");
ButtonGroup size = new ButtonGroup();
size.add(small);
size.add(medium);
size.add(large); // select one, and the others clearThe buttons don’t know about each other. They join a button group, and the javadoc says: “turning “on” one of those buttons turns off all other buttons in the group.”
The group is the hub. In the OpenJDK source, a toggle button’s model hands the request to its group
(“use the group model instead”), and ButtonGroup.setSelected deselects the previous choice and selects
the new one. It works like a mediator, though that is our reading: the javadoc never uses the word.
The Gang of Four’s own example is a font dialog: a FontDialogDirector coordinates a list box, an
entry field and buttons, so that a button is disabled while the entry field is empty and picking an
entry in the list changes the field.
Two look-alikes. The first is the Facade, which also puts one object in front of many. A facade is a front door: the classes behind it never know it exists, and calls only go in. The Gang of Four call its protocol unidirectional. A mediator is different: its colleagues know it, talk back through it, and the protocol is multidirectional. And a facade adds no new behaviour, while a mediator adds the coordination the colleagues couldn’t manage alone.
The second look-alike is the Observer. A subject broadcasts to listeners it doesn’t know, in one direction. A mediator knows exactly who its colleagues are, and decides what each one does.
They team up well. A mediator can listen to its colleagues the Observer way. Observer is the wire. Mediator is the logic.
| Facade | Observer | Mediator | |
|---|---|---|---|
| Direction | in only | one way, outward | both ways |
| Adds behaviour | no | no | yes, the coordination |
| Who knows whom | clients know the facade; the subsystem doesn’t | subjects don’t know their listeners | colleagues know the mediator; it knows them |
When should you skip it? With two objects, a direct reference is fine, like our checkbox and button. If one object simply tells many others what happened, with no rule about who does what, use an observer. If the hub only passes calls along, you’ve built a middleman. And if its rules keep growing, split it before it becomes the biggest class in the project.
Checklist:
changed growing past one screen? (Split the mediator by feature.)Talk to the hub, and keep the hub small.
Related lessons: Facade, Observer, Large Class.
ButtonGroup javadoc.