What It Is
The Mediator pattern moves communication between many objects into one central place. Instead of everyone knowing everyone (and n objects meaning n·n connections), each object knows only the mediator, and the mediator routes.
Example: A Chat Room
Users never hold references to each other. A user sends to the room; the room delivers to everyone else. Joining and leaving touches one list, in one place.
Everyone talks through the room
Ana knows only the room; the room knows everyone. Delivery rules — skip the sender, later maybe mute or private messages — live in exactly one method.
Output: PHP script
<?php
// The mediator: users never talk to each other directly.
class ChatRoom {
/** @var User[] */
private array $users = [];
public function join(User $user): void {
$user->room = $this;
$this->users[] = $user;
}
public function broadcast(User $from, string $msg): void {
foreach ($this->users as $user) {
if ($user !== $from) {
echo $user->name, " receives from ", $from->name, ": ", $msg, "\n";
}
}
}
}
class User {
public ?ChatRoom $room = null;
public function __construct(public string $name) {}
public function send(string $msg): void {
$this->room->broadcast($this, $msg);
}
}
$room = new ChatRoom();
$ana = new User("ana");
$ben = new User("ben");
$cleo = new User("cleo");
$room->join($ana);
$room->join($ben);
$room->join($cleo);
$ana->send("hello everyone");
When to Use It
Use it when many objects coordinate and the web of who-tells-whom is getting dense — chat systems, form fields that enable and disable each other, air-traffic-style coordination.
Skip it for two or three objects with simple links. A mediator between two parties is a middleman nobody hired.
Pros and Cons
Pros: participants stay simple and reusable; the coordination rules are readable in one place; adding a participant touches nothing else.
Cons: the mediator grows — it can quietly become the huge class that knows everything; all traffic through one point can hide performance costs.