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 array, in one place.
Everyone talks through the room
Ana knows only the room; the room knows everyone. One send call prints two lines — ben and cleo receive it, ana does not get her own message back. Delivery rules — skip the sender, later maybe mute or private messages — live in exactly one method.
Output: TypeScript file and captured output
// The mediator: users never talk to each other directly.
class ChatRoom {
private users: User[] = []
join(user: User): void {
user.room = this
this.users.push(user)
}
broadcast(from: User, message: string): void {
for (const user of this.users) {
if (user !== from) {
console.log(user.name, "receives from", from.name + ":", message)
}
}
}
}
class User {
readonly name: string
room: ChatRoom | undefined
constructor(name: string) {
this.name = name
}
send(message: string): void {
this.room?.broadcast(this, message)
}
}
const room = new ChatRoom()
const ana = new User("ana")
const ben = new User("ben")
const 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.