For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/design-patterns/behavioral/mediator.md.

Define an object that centralizes communication between other objects. Many objects communicate in complex ways. You want to reduce direc

Mediator

Overview

Define an object that centralizes communication between other objects.

When to use

  • Many objects communicate in complex ways.
  • You want to reduce direct dependencies between components.

Java example

class ChatMediator {
    private final List<User> users = new ArrayList<>();
    void register(User user) { users.add(user); }
    void broadcast(String msg, User from) {
        for (User u : users) {
            if (u != from) u.receive(msg);
        }
    }
}

class User {
    private final ChatMediator mediator;
    User(ChatMediator mediator) { this.mediator = mediator; }
    void send(String msg) { mediator.broadcast(msg, this); }
    void receive(String msg) { /* ... */ }
}

TypeScript example

class ChatMediator {
  private users: User[] = [];
  register(user: User): void { this.users.push(user); }
  broadcast(msg: string, from: User): void {
    this.users.filter(u => u !== from).forEach(u => u.receive(msg));
  }
}

class User {
  constructor(private mediator: ChatMediator) {}
  send(msg: string): void { this.mediator.broadcast(msg, this); }
  receive(msg: string): void {}
}

Pros and cons

Pros:

  • Reduces coupling between components.
  • Centralizes complex interaction logic.

Cons:

  • Mediator can become too large.
  • Single point of failure.

Common pitfalls

  • Packing domain logic into the mediator.
  • Using mediator for trivial interactions.