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: complete Python program
# The mediator: users never talk to each other directly.
class ChatRoom:
def __init__(self) -> None:
self.users: list["User"] = []
def join(self, user: "User") -> None:
user.room = self
self.users.append(user)
def broadcast(self, sender: "User", msg: str) -> None:
for user in self.users:
if user is not sender:
print(user.name, "receives from", sender.name + ":", msg)
class User:
def __init__(self, name: str) -> None:
self.name = name
self.room: ChatRoom | None = None
def send(self, msg: str) -> None:
if self.room is not None:
self.room.broadcast(self, msg)
room = ChatRoom()
ana = User("ana")
ben = User("ben")
cleo = 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.