Command Palette

Search for a command to run...

PHASE 2Beginner ~7 min· topic 20 of 22Behavioral

Behavioral 8 — Mediator

In one line

Centralize interactions between many objects so they talk to one mediator instead of each other — star topology.

0/22 · 0%

Think of it like this

An airport control tower. Planes don't talk to each other directly; they all talk to the tower, and the tower decides who lands and who waits.

Key ideas

  1. 01

    Solves: many-to-many chatter (chat room, airplane control tower, UI components).

  2. 02

    Colleagues only know the mediator; mediator knows everyone.

  3. 03

    Reduces coupling; risks becoming a god object — keep the mediator's rules thin.

Java / Spring map

  • →

    Spring's ApplicationEventPublisher acts as a mediator between beans; a message broker is the distributed version.

Code & diagrams

ChatRoom.javajava

Users talk only to the room, never directly to each other. N users need N links, not N×N.

public interface ChatMediator {
  void join(User u);
  void leave(User u);
  void send(String from, String msg);
}

public final class ChatRoom implements ChatMediator {
  private final Map<String, User> members = new ConcurrentHashMap<>();

  public void join(User u)  { members.put(u.name(), u); send("system", u.name() + " joined"); }
  public void leave(User u) { members.remove(u.name()); }

  public void send(String from, String msg) {
    for (User u : members.values()) {
      if (!u.name().equals(from)) u.receive(from, msg);   // the rule lives here, in one place
    }
  }
}

public final class User {
  private final String name;
  private final ChatMediator room;
  public User(String name, ChatMediator room) { this.name = name; this.room = room; }
  public String name() { return name; }
  public void say(String msg) { room.send(name, msg); }       // talks to the mediator only
  public void receive(String from, String msg) { System.out.println(name + " <- " + from + ": " + msg); }
}

Explain without notes

01

Mediator vs Observer — when would you pick each in a chat system?

Practice

01

Design the ChatRoom mediator for the Chat HLD (register/leave/broadcast).

Trade-offs

  • ↔

    The mediator can become a single point of failure and a monolith of rules.

Completion checklist

  • I can explain how a mediator turns N×N connections into N and when it becomes a god object.

Back to phase