behavioral

Mediator

Define an object that encapsulates communication between a set of objects, keeping them from referring to each other directly.

Problem

behavioral

Multiple objects need to coordinate behavior, but direct references between them create tight coupling and complex dependencies.

Integration notes

Mediator is useful for chat systems, form coordination, workflow orchestration, and any domain where many components must collaborate without knowing about each other.

Tradeoffs

  • The mediator can become large and complex if it takes on too much coordination logic.
  • Centralizing behavior can make the mediator a single point of failure if it is poorly designed.

Languages

typescript, java, python, angular, react, react-native, csharp, dotnet

Platforms

Web, Backend, Mobile, UI kits, Cross-platform systems

Variants

Scenarios

Chat room mediator

Users send messages through a chat room mediator instead of talking to each other directly.

Language examples

Core languages

Frameworks and libraries

Chat room mediatortypescript

The chat room mediator routes messages between users so they do not need direct references to one another.

TypeScript
interface ChatMediator {
  sendMessage(message: string, user: User): void;
  registerUser(user: User): void;
}


class User {
  constructor(
    public name: string,
    private mediator: ChatMediator
  ) {}


  send(message: string): void {
    this.mediator.sendMessage(message, this);
  }


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


class ChatRoom implements ChatMediator {
  private users: User[] = [];


  registerUser(user: User): void {
    this.users.push(user);
  }


  sendMessage(message: string, user: User): void {
    for (const participant of this.users) {
      if (participant !== user) {
        participant.receive(`${user.name}: ${message}`);
      }
    }
  }
}


const chatRoom = new ChatRoom();
const alice = new User("Alice", chatRoom);
const bob = new User("Bob", chatRoom);
const clara = new User("Clara", chatRoom);


chatRoom.registerUser(alice);
chatRoom.registerUser(bob);
chatRoom.registerUser(clara);


alice.send("Hello everyone!");
bob.send("Hi Alice!");

Real-world examples

  • Chat servers: Group chats and messaging services route messages through a central server rather than peer-to-peer links.
  • Air traffic control: Aircraft coordinate with a control tower that manages timing, safety, and sequencing.
  • Form coordination: Complex forms often use a central controller to coordinate fields, validation, and submission state.