BehavioralTypeScriptverifiedVerified

Mediator Pattern in TypeScript

Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.

How to Implement the Mediator Pattern in TypeScript

1Step 1: Define the Mediator interface and participant base class

interface Mediator {
  notify(sender: ChatParticipant, message: string): void;
}

abstract class ChatParticipant {
  constructor(
    protected readonly name: string,
    protected mediator: Mediator
  ) {}

  send(message: string): void {
    console.log(`[${this.name}] sends: ${message}`);
    this.mediator.notify(this, message);
  }

  receive(from: string, message: string): void {
    console.log(`[${this.name}] received from ${from}: ${message}`);
  }
}

class User extends ChatParticipant {}

2Step 2: Implement the ChatRoom as a concrete mediator

class ChatRoom implements Mediator {
  private participants: ChatParticipant[] = [];

  join(participant: ChatParticipant): void {
    this.participants.push(participant);
  }

  notify(sender: ChatParticipant, message: string): void {
    for (const participant of this.participants) {
      if (participant !== sender) {
        (participant as User).receive(
          (sender as unknown as { name: string }).name,
          message
        );
      }
    }
  }
}

3Step 3: Connect participants and exchange messages

const room = new ChatRoom();
const alice = new User("Alice", room);
const bob = new User("Bob", room);
const carol = new User("Carol", room);

room.join(alice);
room.join(bob);
room.join(carol);

alice.send("Hello everyone!");
// Bob received from Alice: Hello everyone!
// Carol received from Alice: Hello everyone!

Mediator Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mediator Pattern in the Real World

An air traffic control tower is the classic example. Instead of every plane communicating directly with every other plane—a chaotic and dangerous mess—all aircraft talk only to the control tower. The tower mediates all interactions, directing each plane based on the overall picture it maintains. Planes are decoupled from each other entirely.