Card 05/ 08
Mediator Example: A Chat Room
Users send to the room, and the room delivers to everyone else.
A chat room is a Mediator in which the colleagues are many and all alike. Each user sends a message to the room, and the room delivers it to every other member. No user holds a reference to another, so users can join and leave without anyone else changing. This card shows the room in TypeScript.
class ChatRoom {
private readonly members: User[] = [];
join(user: User): void {
this.members.push(user);
this.broadcast(user, `${user.name} joined`);
}
send(from: User, text: string): void {
this.broadcast(from, `${from.name}: ${text}`);
}
private broadcast(from: User, line: string): void {
for (const member of this.members) {
if (member !== from) {
member.receive(line);
}
}
}
}
class User {
constructor(readonly name: string, private readonly room: ChatRoom) {}
say(text: string): void {
this.room.send(this, text);
}
receive(line: string): void {
console.log(` [${this.name} sees] ${line}`);
}
}
const room = new ChatRoom();
const ana = new User("Ana", room);
const ben = new User("Ben", room);
const cleo = new User("Cleo", room);
room.join(ana);
room.join(ben);
room.join(cleo);
console.log("Ben says hello:");
ben.say("hello"); [Ana sees] Ben joined
[Ana sees] Cleo joined
[Ben sees] Cleo joined
Ben says hello:
[Ana sees] Ben: hello
[Cleo sees] Ben: helloEach join is announced to the members already in the room, so Ana sees two joins and Cleo sees none. When Ben says hello, Ana and Cleo see it and Ben does not. User.say calls room.send, and the decision of who receives what is made in broadcast.
This differs from the booking form in what the mediator decides. The dialog had a rule for each kind of field; the room has one rule for every user. Both share the structure: colleagues hold the mediator, not each other, and the mediator alone knows who must hear about an event.
It also looks like Observer, since each message reaches several users. The difference is that in Observer the object that changes notifies its own subscribers. Here every user is both a sender and a receiver, and the room sits between them.
← → move through sections and cards