Behavioral Intermediary Controller

Mediator

Mediator is a behavioral pattern that pulls the web of interactions between a group of objects out into a separate go-between object, so the objects themselves no longer need to know about each other.

Complexity
Popularity

Problem

A group chat app lets several users exchange messages. If every user object calls every other user object directly to deliver a message, each user ends up hardcoding references to everyone else currently in the room.

It works with three people, but drop in a fourth and you have to rewire every existing user to know about them. Remove someone and the same rewiring happens in reverse. The web of direct references becomes a tangle that's hard to follow and even harder to change.

Solution

Mediator pulls all the cross-references out of the users and moves them into one dedicated coordinator object - the chat room. Users stop calling each other directly; instead, each one sends its message to the chat room through a single method, and the chat room looks up everyone currently registered and delivers the message to them.

A user that wants to say something now just tells the chat room and forgets about who's listening. The chat room is the only place that knows the full list of participants, so users can join or leave without any other user's code changing.

When to Use

  • Reach for Mediator when a set of objects references so many of each other's methods that changing one ripples through the rest.
  • Use it when a component can't be dropped into a new context because it's wired directly into a specific set of collaborators.
  • Consider it when subclassing components just to vary how they react to each other has produced a pile of near-duplicate classes.

Real-World Examples

  • **Air traffic control towers** - aircraft never negotiate runway access with each other; every request and clearance passes through the tower.
  • **React Context / centralized state stores** - components dispatch actions to a shared store instead of passing callbacks down through every sibling.
  • **Message brokers like RabbitMQ** - publishers and consumers never connect to each other directly; the broker routes every message between them.