Design Patterns

Pattern 16 of 23, Behavioral family

Mediator

Reduce chaotic dependencies between objects by forcing them to communicate through a central mediator object.

The problem

In a chat, if every user keeps a reference to all the others, adding one person means updating everyone: N objects = N² links.

The solution

Objects no longer know about each other; they only talk to the mediator (ChatRoom), which knows what to forward to whom.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. Alice only knows the ChatRoom, not the other users.
  2. ChatRoom (mediator) → Bob: receive
  3. ChatRoom (mediator) → Chloé: receive
  4. The mediator broadcasts: each object has a single link.
  5. David replies, still through the mediator.
  6. ChatRoom (mediator) → Alice: receive
  7. ChatRoom (mediator) → Bob: receive
  8. Adding a user does not change any other user.

An analogy

An airport control tower: pilots do not talk to each other, they all go through the tower.

When to use it

  • Tightly interconnected components (forms, UI)
  • Chat, event bus, orchestration
  • CQRS (MediatR in .NET)

Pros and cons

Pros

  • Reduced coupling: N links instead of N²
  • Centralized coordination logic
  • Components reusable in isolation

Cons

  • The mediator can turn into a "god object"
  • Central point of failure

Implementations

The same example, written idiomatically in each language.

Mediator in Python

mediator.py 30 lines
class ChatRoom:                              # the mediator
    def __init__(self):
        self.users: list["User"] = []

    def join(self, user: "User"):
        self.users.append(user)
        user.room = self

    def broadcast(self, sender: "User", msg: str):
        for u in self.users:
            if u is not sender:
                u.receive(sender.name, msg)


class User:
    def __init__(self, name: str):
        self.name, self.room = name, None

    def send(self, msg: str):
        self.room.broadcast(self, msg)

    def receive(self, frm: str, msg: str):
        print(f"[{self.name}] {frm}: {msg}")


room = ChatRoom()
alice, bob = User("Alice"), User("Bob")
room.join(alice)
room.join(bob)
alice.send("Hi!")

Mediator in TypeScript

mediator.ts 26 lines
class ChatRoom {
  private users = new Set<User>();

  join(u: User) {
    this.users.add(u);
    u.room = this;
  }

  broadcast(from: User, msg: string) {
    for (const u of this.users) if (u !== from) u.receive(from.name, msg);
  }
}

class User {
  room?: ChatRoom;
  constructor(public name: string) {}

  send(msg: string) { this.room?.broadcast(this, msg); }
  receive(from: string, msg: string) { console.log("[" + this.name + "] " + from + ": " + msg); }
}

const room = new ChatRoom();
const alice = new User("Alice"), bob = new User("Bob");
room.join(alice);
room.join(bob);
alice.send("Hi!");

Mediator in Java

mediator.java 27 lines
class ChatRoom {
    private final List<User> users = new ArrayList<>();

    void join(User u) {
        users.add(u);
        u.room = this;
    }

    void broadcast(User from, String msg) {
        users.stream()
             .filter(u -> u != from)
             .forEach(u -> u.receive(from.name, msg));
    }
}

class User {
    final String name;
    ChatRoom room;

    User(String name) { this.name = name; }

    void send(String msg) { room.broadcast(this, msg); }

    void receive(String from, String msg) {
        System.out.printf("[%s] %s: %s%n", name, from, msg);
    }
}

Mediator in C#

mediator.cs 22 lines
class ChatRoom
{
    private readonly List<User> _users = [];

    public void Join(User u) { _users.Add(u); u.Room = this; }

    public void Broadcast(User from, string msg)
    {
        foreach (var u in _users.Where(u => u != from)) u.Receive(from.Name, msg);
    }
}

class User(string name)
{
    public string Name => name;
    public ChatRoom? Room { get; set; }

    public void Send(string msg) => Room?.Broadcast(this, msg);
    public void Receive(string from, string msg) => Console.WriteLine($"[{Name}] {from}: {msg}");
}

// .NET: the MediatR library applies this pattern to commands / queries (CQRS)

Mediator in PHP

mediator.php 34 lines
final class ChatRoom
{
    /** @var User[] */
    private array $users = [];

    public function join(User $u): void
    {
        $this->users[] = $u;
        $u->room = $this;
    }

    public function broadcast(User $from, string $msg): void
    {
        foreach ($this->users as $u) {
            if ($u !== $from) {
                $u->receive($from->name, $msg);
            }
        }
    }
}

final class User
{
    public ?ChatRoom $room = null;

    public function __construct(public string $name) {}

    public function send(string $msg): void { $this->room->broadcast($this, $msg); }

    public function receive(string $from, string $msg): void
    {
        echo "[{$this->name}] $from: $msg", PHP_EOL;
    }
}

Mediator in Go

mediator.go 28 lines
type Message struct{ From, Text string }

type ChatRoom struct {
    mu    sync.Mutex
    users map[string]chan Message
}

func NewChatRoom() *ChatRoom {
    return &ChatRoom{users: map[string]chan Message{}}
}

func (r *ChatRoom) Join(name string) <-chan Message {
    r.mu.Lock()
    defer r.mu.Unlock()
    ch := make(chan Message, 16)
    r.users[name] = ch
    return ch
}

func (r *ChatRoom) Broadcast(m Message) {
    r.mu.Lock()
    defer r.mu.Unlock()
    for name, ch := range r.users {
        if name != m.From {
            ch <- m
        }
    }
}

Frequently asked questions

What is the Mediator design pattern?

Reduce chaotic dependencies between objects by forcing them to communicate through a central mediator object. Objects no longer know about each other; they only talk to the mediator (ChatRoom), which knows what to forward to whom.

When should you use the Mediator pattern?

Tightly interconnected components (forms, UI); Chat, event bus, orchestration; CQRS (MediatR in .NET).

What are the pros and cons of the Mediator pattern?

Pros: Reduced coupling: N links instead of N²; Centralized coordination logic; Components reusable in isolation. Cons: The mediator can turn into a "god object"; Central point of failure.