# MediatorA 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.

{{< lesson-video youtube="lLf1pdh-G_Q" title="Mediator" >}}

## Twenty conversations

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.

```mermaid {alt="Five widgets (email, password, confirm, terms, submit) joined by links in every direction, each pair connected; the enable rule is copied into four of them and one copy forgot the terms checkbox." caption="Five widgets, twenty links, four copies of one rule."}
flowchart LR
  E["email"] <--> P["password"]
  E <--> C["confirm"]
  E <--> T["terms"]
  E <--> S["submit"]
  P <--> C
  P <--> T
  P <--> S
  C <--> T
  C <--> S
  T <--> S
  class E,P,C,T,S bad
```

## The pass

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**.

```mermaid {alt="Left: four stations (grill, fryer, salad, dessert) joined to each other by shouting. Right: the same four stations each talk only to the expediter, who calls the orders back." caption="Shouting across the kitchen versus telling the expediter."}
flowchart LR
  subgraph before["No one in charge"]
    direction TB
    G1["grill"] <--> F1["fryer"]
    S1["salad"] <--> D1["dessert"]
    G1 <--> S1
    F1 <--> D1
  end
  subgraph after["An expediter at the pass"]
    direction TB
    G2["grill"] --> X["expediter"]
    F2["fryer"] --> X
    S2["salad"] --> X
    D2["dessert"] --> X
    X --> F2
  end
  before ~~~ after
  class G1,F1,S1,D1 bad
  class X good
  class G2,F2,S2,D2 c5
```

## The obvious version: widgets that hold each other

Start with two widgets. The checkbox should enable the submit button, so it holds a reference to the
button.

```java
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.

## Why it breaks

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.

```java
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.

## The key idea: one hub

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.

```mermaid {alt="Before: five widgets wired directly to each other, a few of the twenty links shown. After: each of the five widgets has one line to a single Mediator box, five links in all." caption="Many-to-many becomes one-to-many."}
flowchart TB
  subgraph before["Before: widgets wired to each other (6 of 20 links shown)"]
    direction TB
    a1["email"] <--> a2["password"]
    a2 <--> a3["confirm"]
    a3 <--> a4["terms"]
    a4 <--> a5["submit"]
    a1 <--> a5
    a2 <--> a4
  end
  subgraph after["After: one hub, five links"]
    direction LR
    b1["email"] <--> M["Mediator"]
    b2["password"] <--> M
    b3["confirm"] <--> M
    b4["terms"] <--> M
    b5["submit"] <--> M
  end
  before ~~~ after
  class a1,a2,a3,a4,a5 bad
  class M good
  class b1,b2,b3,b4,b5 c5
```

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.**

## Building it

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.

```java
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.

```java
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.

```java
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`.** Passing `this` from 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 a `register(widget)` method.

Follow one click. The user ticks the box. The checkbox calls `changed`. The dialog reads every widget
and enables the button.

```mermaid {alt="Sequence: the user toggles the terms Checkbox; the Checkbox calls changed with itself on SignupDialog; SignupDialog reads email, password, confirm and terms, then calls setEnabled on the submit Button." caption="One click, one decision, in one place."}
sequenceDiagram
  actor U as user
  participant T as terms (Checkbox)
  participant D as SignupDialog
  participant B as submit (Button)
  U->>T: toggle()
  T->>D: changed(terms)
  Note over D: reads email, password,<br/>confirm and terms
  D->>B: setEnabled(true)
```

Add a hint label that says passwords differ, and it's one new field and one new line in the dialog. No
widget changes.

```java
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.

```java
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());
    }
}
```

## Anatomy and design choices

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.

```mermaid {alt="Class diagram: SignupDialog implements the Mediator interface and holds TextField, Checkbox and Button; each of those extends Widget, which holds a Mediator." caption="Three roles."}
classDiagram
  class Mediator {
    <<interface>>
    changed(source)
  }
  class SignupDialog {
    changed(source)
  }
  class Widget {
    mediator
  }
  class TextField
  class Checkbox
  class Button
  Mediator <|.. SignupDialog
  Widget <|-- TextField
  Widget <|-- Checkbox
  Widget <|-- Button
  Widget --> Mediator : reports to
  SignupDialog o--> Widget : holds and tells
```

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:

- **How a colleague reports.** Passing itself, as ours does, tells the mediator who changed. Or the
  mediator can listen to each widget as a subscriber, the Observer way. The Gang of Four describe both:
  the mediator as an Observer with colleagues as subjects, or a notification method where the colleague
  passes itself as an argument.
- **The interface is optional.** If your widgets will only ever have one mediator, a concrete class is
  enough. The abstraction pays off when the same colleagues work with different mediators, like our
  login and signup dialogs.

## The cost: a growing hub

Now the price. The mediator collects every rule. Add widgets and `changed` grows. Add features and it
grows more.

```java
@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](/code-smells/large-class/) smell
in a new costume.

Three habits keep it small:

1. **Let each widget keep its own rules.** The email field knows what a valid email is, so the dialog
   only asks.

```java
@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:

```java
// added to TextField
public boolean isValid() { return text.contains("@"); }
public boolean matches(TextField other) { return text.equals(other.text); }
```

2. **One mediator per feature.** A signup dialog and a billing panel get separate mediators.
3. **If the hub only forwards calls and decides nothing, remove it.**

## In the JDK: `ButtonGroup`

Swing has a small one. A size menu with three radio buttons: small, medium, large. Choosing one has to
clear the other two.

```java
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 clear
```

The buttons don't know about each other. They join a button group, and the
[javadoc](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/ButtonGroup.html)
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.

```mermaid {alt="Sequence: the user selects the Large radio button; its model asks the ButtonGroup to select it; the ButtonGroup deselects Medium, the old choice, and selects Large." caption="The group deselects the old choice."}
sequenceDiagram
  actor U as user
  participant L as Large (radio)
  participant G as ButtonGroup
  participant M as Medium (radio)
  U->>L: click
  L->>G: select me
  G->>M: deselect
  G->>L: select
```

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.

## Facade or observer?

Two look-alikes. The first is the [Facade](/patterns/facade-pattern/), 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](/patterns/observer-pattern/). 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.

```mermaid {alt="Three small pictures side by side: a facade with arrows only going in to the classes behind it; an observer subject broadcasting one way to several listeners; a mediator hub with two-way arrows to its colleagues, deciding what each does." caption="Front door, broadcast, hub."}
flowchart LR
  subgraph fac["Facade"]
    direction TB
    f0["client"] --> f1["facade"]
    f1 --> f2["A"]
    f1 --> f3["B"]
  end
  subgraph obs["Observer"]
    direction TB
    o1["subject"] --> o2["listener"]
    o1 --> o3["listener"]
  end
  subgraph med["Mediator"]
    direction TB
    m1["hub"] <--> m2["colleague"]
    m1 <--> m3["colleague"]
  end
  fac ~~~ obs ~~~ med
  class f1 c1
  class o1 muted
  class m1 good
```

| | 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 not to use it

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.

```mermaid {alt="Decision: only two objects? Use a direct reference. Plain one-way broadcast with no coordination rules? Use an observer. Does the hub only pass calls along? Remove it. Otherwise use a mediator, and split it by feature when its rules keep growing." caption="A hub has to earn its place."}
flowchart TD
  Q1{"Only two objects?"} -->|yes| A1["direct reference"]
  Q1 -->|no| Q2{"Just a broadcast,<br/>no rules?"}
  Q2 -->|yes| A2["observer"]
  Q2 -->|no| Q3{"Would the hub only<br/>forward calls?"}
  Q3 -->|yes| A3["no hub: remove the middleman"]
  Q3 -->|no| A4["mediator,<br/>one per feature"]
  class A4 good
  class A3 warn
```

## Recap

- When many objects talk to many objects, nobody can change anything safely.
- Give them one hub. Each colleague reports to the mediator, and the mediator decides who reacts.
- Twenty links become five, and the rules live in one place.
- The price is a growing hub, so keep each mediator small and split it by feature.
- It's not a facade, because the colleagues know it. And it's not an observer, because it makes decisions.

```mermaid {alt="Recap chain: tangled links, one hub, rules in one place, keep the hub small." caption="Talk to the hub, and keep the hub small."}
flowchart LR
  A["many-to-many chatter"] --> B["one mediator"] --> C["rules in one place"] --> D["a small hub"]
  class B good
  class A bad
```

Checklist:

- Do several objects hold references to each other, and does one rule live in more than one of them?
- Do the colleagues only need to say "I changed", and not who cares?
- Does the mediator decide, or does it only forward? (If it only forwards, remove it.)
- Is each widget keeping its own rules, with the hub only coordinating?
- Is `changed` growing past one screen? (Split the mediator by feature.)

> **Talk to the hub, and keep the hub small.**

Related lessons: [Facade](/patterns/facade-pattern/), [Observer](/patterns/observer-pattern/),
[Large Class](/code-smells/large-class/).

## Further reading

- Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, *Design Patterns* (1994): Mediator.
- refactoring.guru: [Mediator](https://refactoring.guru/design-patterns/mediator).
- [`ButtonGroup`](https://docs.oracle.com/en/java/javase/21/docs/api/java.desktop/javax/swing/ButtonGroup.html) javadoc.
