Skip to content
BBaskaran

Mediator

Reduce coupling by making objects communicate through a central mediator.

Use it when

Many objects talk to each other in complex ways that are hard to change.

/**
 * Mediator: users talk through a chat room instead of directly to each other.
 *
 * Real-world scenario: a team chat app. If every user kept a link to every other
 * user, adding one person would mean updating everyone. Instead, users only know
 * the chat room. The room (the mediator) decides who receives each message: all
 * other members for a normal message, or just one for a private message.
 */

// Mediator: the only object that knows all the members and routes messages.
class ChatRoom {
  readonly name: string;
  private readonly members = new Map<string, User>();

  constructor(name: string) {
    this.name = name;
  }

  join(user: User): void {
    this.members.set(user.name, user);
  }

  send(sender: string, text: string, to?: string): void {
    if (to !== undefined) {
      this.members.get(to)?.receive(sender, `(private) ${text}`);
      return;
    }
    for (const [name, member] of this.members) {
      if (name !== sender) {
        member.receive(sender, text);
      }
    }
  }
}

// Colleague: knows only the room, never the other users.
class User {
  readonly name: string;
  private readonly room: ChatRoom;

  constructor(name: string, room: ChatRoom) {
    this.name = name;
    this.room = room;
    room.join(this);
  }

  send(text: string, to?: string): void {
    console.log(`${this.name} sends: ${text}`);
    this.room.send(this.name, text, to);
  }

  receive(sender: string, text: string): void {
    console.log(`  ${this.name} sees ${sender}: ${text}`);
  }
}

function clientCode(): void {
  const room = new ChatRoom("#release");
  const asha = new User("Asha", room);
  const ravi = new User("Ravi", room);
  new User("Meena", room);

  asha.send("Release is at 5pm");
  ravi.send("Can you review my PR first?", "Asha");
}

clientCode();

// Output:
// Asha sends: Release is at 5pm
//   Ravi sees Asha: Release is at 5pm
//   Meena sees Asha: Release is at 5pm
// Ravi sends: Can you review my PR first?
//   Asha sees Ravi: (private) Can you review my PR first?

How it works

RoleClassesWhat it does
MediatorChatRoomKnows every member (in a Map) and decides who receives each message
ColleagueUserSends and receives through the room; never holds a link to another user
ClientclientCode()Creates the room, adds users and has them chat