Skip to content
Veltoryx Technologies
ProLesson 7.4Intermediate7 min readUpdated 31 October 2026

Mediator Pattern

Learn how to stop objects talking to each other directly by routing their communication through one central object, using a chat room and a form example, and how it differs from Observer.

At a busy airport, hundreds of planes take off and land every day. Imagine if every pilot had to talk to every other pilot to avoid collisions: "I am at 5,000 feet, who is near me? Who is landing? Please move." It would be chaos. Instead, every plane talks to one place: the control tower. The tower knows where everyone is and tells each pilot what to do. Pilots never talk to each other directly, and a new plane only needs to learn how to talk to the tower.

The Mediator pattern puts a control tower into your code. Instead of many objects holding references to many other objects, they all talk to one mediator object, and the mediator coordinates them. It is the last of the behavioral patterns in this module.

01The problem: a web of connections

Consider a chat application. Each user can send a message to all the others in the room. A direct approach makes every user hold a list of every other user:

Before: every user knows every other user
public class User {
    private final String name;
    private final List<User> otherUsers = new ArrayList<>();

    public void connectTo(User other) { otherUsers.add(other); }

    public void say(String message) {
        for (User other : otherUsers) {
            other.receive(name, message);
        }
    }
    public void receive(String from, String message) { /* show it */ }
}

For four people, you need to connect every pair: six connections. For ten people, forty-five. For a hundred, nearly five thousand. Every time someone joins or leaves, every other user must be updated. And if you add a rule such as "do not deliver messages to people who muted the sender", you must change the code in the User class, which is now spread across everyone.

The same mess appears in user interfaces. A sign-up form has a checkbox "I have a coupon", a text box for the code, a country drop-down that fills a state drop-down, and a submit button that should be enabled only when all is valid. If each control knows about the others, they form a tangle: the checkbox enables the text box, the text box tells the button, the country tells the state list, and any new control must be wired to many others.

Four people connected to each other need six links, while four people connected to a chat room need only four
Fig. 1 · Four people connected to each other need six links, while four people connected to a chat room need only four

Loading the rest of the lesson…