Skip to content

Mediator

Difficulty: Intermediate

Key concepts

  • mediator pattern
  • colleagues
  • many-to-many coupling
  • centralized interaction rules
  • re-entrant delivery
  • god mediator
  • The problem Mediator solves, shown before the pattern is named: several objects must coordinate, and the links between them grow with every pair.
  • How to decide what the mediator knows, what each colleague knows, and where a rule about two objects belongs.
  • A C++ chat room that owns its participants, keeps every delivery rule in one function, and stays correct when a participant answers while the room is delivering.
  • How to keep the mediator from becoming a god class, and when you should not use a mediator at all.

A team-chat app has rooms. People join and leave a room while it runs, and the app also lets bots join, small programs that answer commands.

Requirements:

  1. FR-1 A member can post a message to everyone else in the room.
  2. FR-2 A member can send a direct message to one other member; nobody else sees it.
  3. FR-3 A member can block another member, so that they no longer see that member’s messages. Blocking affects only the member who blocks.
  4. FR-4 Members and bots join and leave at any time, and everyone present is told when someone joins or leaves.
  5. FR-5 A bot answers the command !rules by posting the room’s rules. Everyone sees the question before the answer.

Non-functional requirements:

  • NFR-1 Single-threaded: all messages are handled on one thread.
  • NFR-2 A new delivery rule (for example, muting a member for an hour) must be added in one place.
Every message goes through the room, which decides who receives it
Text description of the diagram

A solid arrow is a flow of messages. Ana’s chat window, Ben’s chat window, and the rules bot each send their posts, direct messages, and blocks to the chat room. The chat room delivers to each of them only what that participant should see. (In the code below, main plays the app: it calls the room on each window’s behalf.)

Diagram source (Mermaid)
flowchart LR
ANA["ana's chat window"] -->|"posts, sends, blocks"| ROOM["chat room"]
BEN["ben's chat window"] -->|"posts, sends, blocks"| ROOM
BOT["rules bot"] -->|"posts answers"| ROOM
ROOM -->|"delivers what each should see"| ANA
ROOM -->|"delivers what each should see"| BEN
ROOM -->|"delivers what each should see"| BOT

Where Mediator shows up in requirements. Listen for rules that involve two or more objects at once: “A sees B’s message unless A blocked B”, “when this box is ticked, that field is enabled and the button is disabled”, “a plane may land only if no other plane is on the runway”. In code, the signal is a set of peer objects that each hold pointers to several of the others, and a change in one rule that touches all of them. Mediator comes up sometimes: in user-interface dialogs, in chat and game rooms, and in workflows where several parts must take turns.

Let each member keep a list of the members it has met, and send its messages to them directly:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// Every member keeps links to every other member it has met, and checks
// the others' rules itself.
// The design without a mediator: members point straight at each other.
// Two members can talk only after one of them has called meet() on the
// other, so a room of four needs six meet() calls. The links are plain
// pointers (Member*) that observe, not own, so each member must remove
// itself from everyone's list before it is destroyed.
class Member final {
public:
explicit Member(std::string name) : name_{std::move(name)} {}
// Unlink on the way out, or the others keep a dangling pointer to
// this member and the next post would use a destroyed object.
~Member() { leave(); }
Member(const Member&) = delete; // others hold its address
Member& operator=(const Member&) = delete;
void meet(Member& other); // links both ways; every pair must meet once
void leave(); // unlinks from everyone it met
void post(const std::string& text); // to every member it has met
// To one member it has met; throws std::invalid_argument for anyone
// else, even someone who exists but was never introduced.
void send(const std::string& to, const std::string& text);
void block(const std::string& name) { blocked_.insert(name); }
const std::string& name() const { return name_; }
const std::vector<std::string>& inbox() const { return inbox_; }
private:
void deliver_from(const Member& sender, const std::string& line);
std::string name_;
std::vector<Member*> contacts_; // everyone it has met
std::set<std::string> blocked_; // names whose messages it refuses
std::vector<std::string> inbox_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// The sender itself walks its contacts and hands each one the line. A
// member it has not met is simply missed: nothing reports it.
void Member::post(const std::string& text) {
for (Member* contact : contacts_) {
contact->deliver_from(*this, name_ + ": " + text);
}
}
// Search the contacts for the name. The early return stops at the first
// match; reaching the end of the loop means "not one of my contacts".
void Member::send(const std::string& to, const std::string& text) {
for (Member* contact : contacts_) {
if (contact->name_ == to) {
contact->deliver_from(*this, name_ + " (direct): " + text);
return;
}
}
throw std::invalid_argument{"no member named " + to};
}
// The blocking rule lives here, inside each member; a new rule (muting,
// a "do not disturb" mode) is a change to every member.
// Runs on the receiving member: it keeps the line unless it has blocked
// the sender's name.
void Member::deliver_from(const Member& sender, const std::string& line) {
if (!blocked_.contains(sender.name_)) {
inbox_.push_back(line);
}
}

It works for two or three people who all know each other, and it is easy to follow. Then a third person is introduced to only one of them:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_room.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false. LLD_CHECK_EQ(actual, expected) does the same
// for actual == expected and also prints both values when they differ.
// They come from the site's small test header, lld_test.hpp.
//
// Three members, but only two introductions: ana knows ben, ben knows cai.
// ana's post reaches ben and silently misses cai.
LLD_TEST(before_a_member_reaches_only_the_members_it_has_met) {
before::Member ana{"ana"};
before::Member ben{"ben"};
before::Member cai{"cai"};
ana.meet(ben);
ben.meet(cai); // nobody introduced ana and cai
ana.post("hi");
LLD_CHECK_EQ(ben.inbox().size(), std::size_t{1});
LLD_CHECK(cai.inbox().empty()); // three members need three meet calls
}

It fails three of the requirements:

  • FR-1 fails. A post reaches only the members its sender has met, so “everyone in the room” depends on who called meet. With n members, the room needs n(n − 1)/2 links, and every new member must be linked to every member already there.
  • FR-4 has no home. “Tell everyone when someone joins” needs somebody who knows everyone. No member does, and leave must unlink from every contact, through raw pointers in both directions.
  • NFR-2 fails. The blocking rule lives inside Member. A bot is a different class, so it would need its own copy of the rule, and a new rule such as muting changes every class that can receive a message.

Before naming a pattern, ask of each piece of data and each job: who needs to know this to do their work?

Data Who needs it Where it goes
a participant’s name everyone who addresses or shows it the participant
the lines shown in a chat window only that window Member
the rules text a bot answers with only that bot RulesBot
who is in the room posting to “everyone”, join and leave notices the room
who has blocked whom the decision to deliver, which involves two people the room, not either member
messages waiting to be delivered the delivery loop the room
Job Who does it Why there
post, send, block, join, leave the room, asked by the app on a participant’s behalf, or by a participant inside receive they change or use who is present
decide whether a reader gets a message the room, in one private function the rule involves the reader, the sender, and the blocks (NFR-2)
show a message as a line of text Member how a window looks is not the room’s business
answer !rules RulesBot it is the bot’s own behaviour

Two rows decide the design. A block is a fact about a pair, so putting it in one member (as the straightforward solution did) means the other side cannot see it, and putting it in both means keeping two copies in step. It belongs to the object that knows every pair: the room. And formatting a line is not a delivery decision, so it stays in the window, even though the room is the one calling the window. That second row is the first defence against a god mediator.

When a set of objects must coordinate, and the rules about who affects whom involve several of them, give the coordination to one object. The peers, called colleagues, know only that object, never each other. That is the Mediator pattern.

The roles here:

  • Mediator: ChatRoom. It knows who is present and holds the rules. It decides who receives each message.
  • Colleague: Participant, an abstract class whose one virtual function is receive. Member (a chat window) and RulesBot are the concrete colleagues.
  • Client: main, which stands in for the app: it creates participants, puts them in the room, and asks the room to post on a participant’s behalf.

The classic description gives the mediator its own abstract interface too, so colleagues can work with several kinds of mediator. We leave it out: there is one kind of room, and the colleagues are tested through the real room. Add the interface when a second kind of room appears, not before.

class ChatRoom final

the mediator

Data members

  • std::vector<std::unique_ptr<Participant>> present_; owns them, in joining order
  • std::set<std::pair<std::string, std::string>> blocks_; (who, blocked)
  • std::deque<Message> pending_; posted, not yet delivered
  • bool delivering_;

Member functions

  • Participant& join(std::unique_ptr<Participant> participant);
  • void leave(const std::string& name);
  • void post(const std::string& from, std::string text);
  • void send(const std::string& from, const std::string& to, std::string text);
  • void block(const std::string& who, const std::string& blocked);

class Participant

abstract: a colleague; not copyable or movable

Data members

  • std::string name_;

Member functions

  • virtual void receive(const Message& message, ChatRoom& room) = 0;

class Member final

a Participant: a chat window

Data members

  • std::vector<std::string> inbox_; lines as shown

class RulesBot final

a Participant

Data members

  • std::string rules_;
  • int answered_;
The room knows everyone and every rule; each participant knows only how to receive
The room owns the participants and the rules; participants use the room only while it calls them
Text description of the diagram

A solid arrow means “owns”, a dashed arrow means “uses”, and a thick arrow means “implements”. Main owns the ChatRoom (the mediator). The room owns each Participant through a unique_ptr, and owns the blocks and the pending messages. The room calls receive on participants, and a participant may post through the room it was given in that call. Member and RulesBot implement Participant.

Diagram source (Mermaid)
flowchart TB
MAIN["main"] -->|owns| ROOM["ChatRoom<br/>mediator"]
ROOM -->|"owns, unique_ptr"| PART["Participant<br/>colleague interface"]
ROOM -->|owns| RULES["blocks and<br/>pending messages"]
ROOM -.->|"calls receive"| PART
PART -.->|"posts through the room<br/>it was given"| ROOM
MEMBER["Member"] ==>|implements| PART
BOT["RulesBot"] ==>|implements| PART

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

message.hpp
// One message, as a plain value: copied or moved like an int, with no
// pointers to anyone. The room reads `from` and `to` to decide who gets it.
// Brace lists such as {"ana", "", "hi"} fill the fields in this order.
struct Message {
std::string from; // empty for the room's own notices ("ana joined")
std::string to; // empty for everyone; a name for a direct message
std::string text;
};

A Message is a plain value: who sent it, who it is for, and the text. An empty from marks the room’s own notices; an empty to means everyone.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

participant.hpp
// Anyone in a room: a person's chat window, or a bot. A participant
// never talks to another participant, only to the room it is given.
// It is the "colleague" interface of the pattern: each kind of
// participant derives from it and supplies receive().
class Participant {
public:
// Virtual, because the room deletes participants through a pointer to
// this base class; the derived destructor must run too.
virtual ~Participant() = default;
// No copies (and so, here, no moves either): the room hands out
// references to the one object it owns, so each participant has an
// identity that must not be duplicated.
Participant(const Participant&) = delete;
Participant& operator=(const Participant&) = delete;
const std::string& name() const { return name_; }
// Called by the room for each message this participant should see.
// `room` is the room delivering it, for participants that answer.
// `= 0`: pure virtual, so every kind of participant must define it.
virtual void receive(const Message& message, ChatRoom& room) = 0;
protected:
// Only derived classes (Member, RulesBot) can call this. The name is
// fixed here and never changes, because the room finds people by name.
explicit Participant(std::string name) : name_{std::move(name)} {}
private:
std::string name_;
};

Three decisions are in this small class:

  • receive is given the room. A participant does not store a pointer to its room, so there is no back-pointer to keep valid, and a participant cannot outlive “its” room with a dangling reference. The price is that a participant can act only when the room calls it; the app posts on a member’s behalf by calling the room (see design choices).
  • Participants cannot be copied. The room owns each one through a std::unique_ptr and hands out references to it, so a participant is an object with identity. Deleting the copy operations also stops the compiler from generating moves, so participants cannot be moved either; a test checks this with static_assert.
  • The constructor is protected, so only derived classes can create a Participant, and the name is set once and cannot change. The room finds participants by name, so a name that changed after joining would break every rule that uses it.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

chat_room.hpp
// Knows who is present and decides who receives what. Participants know
// only the room. Single-threaded.
// This is the mediator. Every message goes in through post() or send(),
// and the room alone chooses who receives it (the rules are in wants()).
// It owns every participant through a std::unique_ptr, so when a
// participant leaves, or the room is destroyed, the participant is too.
// join() and leave() throw std::logic_error if called during a delivery
// (from inside some participant's receive()).
class ChatRoom final {
public:
// Takes ownership. Throws std::invalid_argument for a null participant,
// an empty name, or a name already present. The reference stays valid
// until that participant leaves or the room is destroyed.
Participant& join(std::unique_ptr<Participant> participant);
// Throws if not present. Takes a copy of the name, because the
// participant, and so its name_, is destroyed here.
void leave(std::string name);
// post, send, and block throw std::invalid_argument for a name that is
// not present. `text` is taken by value and moved into the Message.
void post(const std::string& from, std::string text); // to everyone else
void send(const std::string& from, const std::string& to, std::string text);
// From now on, `who` no longer receives messages from `blocked`. One
// way only: `blocked` still receives messages from `who`.
void block(const std::string& who, const std::string& blocked);
std::size_t size() const { return present_.size(); }
private:
Participant* find(const std::string& name) const; // null if absent
// Like find, but throws std::invalid_argument instead of returning null.
Participant& require(const std::string& name) const;
bool wants(const Participant& reader, const Message& message) const;
void enqueue(Message message);
void deliver(const Message& message);
std::vector<std::unique_ptr<Participant>> present_; // in joining order
std::set<std::pair<std::string, std::string>> blocks_; // (who, blocked)
// A queue: messages join at the back and are delivered from the front,
// in the order they were posted.
std::deque<Message> pending_; // posted, not yet delivered
bool delivering_ = false; // true while enqueue's loop is running
};

The public functions are the only way colleagues affect each other. The private ones hold the rules and the delivery loop. The room owns its participants: join takes a std::unique_ptr and returns a reference that stays valid until that participant leaves or the room is destroyed. leave takes the name by value: a caller may well pass p.name(), a reference into the participant that leave is about to destroy, and a test checks exactly that. For callers who want the concrete type back, a small helper creates the participant in place:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

chat_room.hpp
// Creates a T in the room and returns it as a T&, valid until it leaves.
// T is the participant class, such as Member; Args... stands for any
// number of arguments of any types, here the ones T's constructor takes.
// join_new<Member>(room, "ana") makes a Member named "ana". The caller
// gets back a Member&, not just a Participant&, so it can use inbox().
template <typename T, typename... Args>
T& join_new(ChatRoom& room, Args&&... args) {
// std::forward hands each argument on exactly as it was given, so a
// temporary can be moved rather than copied.
auto participant = std::make_unique<T>(std::forward<Args>(args)...);
// Take the reference first: the move below empties `participant`, but
// the object itself stays where it is, now owned by the room.
T& joined = *participant;
// If join refuses the participant (a bad or duplicate name, or a call
// during a delivery), the object is destroyed and nothing is returned.
// If a receiver throws during the "joined" notice, join throws too, but
// the newcomer is already in the room and stays there.
room.join(std::move(participant));
return joined;
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

chat_room.cpp
// Check everything first, then change. refuse_while (a helper earlier in
// this file) throws std::logic_error if a delivery is running. find
// returns null when the name is free, so `if (find(...))` means "taken".
Participant& ChatRoom::join(std::unique_ptr<Participant> participant) {
refuse_while(delivering_, "join");
if (!participant) {
throw std::invalid_argument{"no participant to join"};
}
if (participant->name().empty()) {
throw std::invalid_argument{"a participant needs a name"};
}
if (find(participant->name())) {
throw std::invalid_argument{participant->name() + " is already here"};
}
// The reference is taken before the move: afterwards `participant` is
// null, but the object has not moved, and present_ now owns it.
Participant& joined = *participant;
present_.push_back(std::move(participant));
// A room notice (empty from and to) to everyone present, including the
// newcomer. If a receiver throws during it, join throws, but the
// newcomer is already in the room.
enqueue({"", "", joined.name() + " joined"});
return joined;
}
void ChatRoom::leave(std::string name) {
refuse_while(delivering_, "leave");
require(name); // only for its check: throws if nobody has this name
// std::erase_if removes every element the lambda says yes to. Erasing
// the unique_ptr destroys the participant. `name` is this function's
// own copy, so it is still valid after the participant is gone.
std::erase_if(present_, [&](const auto& participant) { return participant->name() == name; });
// Forget the blocks made by or against them, so a later newcomer with
// the same name starts with none.
std::erase_if(blocks_, [&](const auto& block) {
return block.first == name || block.second == name;
});
enqueue({"", "", name + " left"}); // they are gone, so they do not see it
}

join checks everything before it changes anything, so a refused join leaves the room as it was. One exception: the notice x joined is delivered after the participant is added, so if a participant throws during that delivery, join throws but the new participant stays in the room. It keeps a reference to the new participant before moving the unique_ptr into the vector: after the move, the local participant is null, but the object it pointed to has not moved. leave destroys the participant (the unique_ptr in present_ is erased) and removes every block that mentions it, so a new participant who later joins with the same name does not inherit old blocks.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

chat_room.cpp
// post, send, and block check every name first (require throws for an
// unknown one), so a mistake is an error, not a lost message. post and
// send never deliver directly: they build a Message and hand it to
// enqueue, which delivers it now or, during a delivery, a little later.
void ChatRoom::post(const std::string& from, std::string text) {
require(from);
enqueue({from, "", std::move(text)});
}
void ChatRoom::send(const std::string& from, const std::string& to, std::string text) {
require(from);
require(to);
enqueue({from, to, std::move(text)});
}
void ChatRoom::block(const std::string& who, const std::string& blocked) {
require(who);
require(blocked);
blocks_.insert({who, blocked}); // a set: blocking twice is harmless
}
// Every delivery rule is here, in one function.
// Should `reader` receive `message`? Each rule that says no returns false
// at once; a message that passes them all is delivered. A room notice has
// an empty `from`, which matches no reader's name and no block, so every
// present participant gets it.
bool ChatRoom::wants(const Participant& reader, const Message& message) const {
if (reader.name() == message.from) {
return false; // nobody receives their own message
}
if (!message.to.empty() && message.to != reader.name()) {
return false; // a direct message for someone else
}
// Last rule: has this reader blocked this sender?
return !blocks_.contains({reader.name(), message.from});
}

wants is the heart of the pattern. Every rule about who receives what is one if in this one function: the sender does not get their own message, a direct message goes only to its recipient, and a reader does not get messages from someone they blocked. Muting (NFR-2) would be one more if here, plus a function and a member to record who is muted; no participant class changes. post, send, and block check names first, so an unknown name is an error, not a silently lost message.

Delivery, and replies during delivery (FR-5)

Section titled “Delivery, and replies during delivery (FR-5)”

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

chat_room.cpp
// A message posted while another is being delivered (a bot answering)
// waits in the queue, so everyone sees a message before any reply to it.
// The first call (from post, send, join, or leave in the app) finds
// delivering_ false and runs the loop until the queue is empty. A call
// made during that loop, from inside some receive(), only adds to the
// queue and returns. If a receive throws, catch (...) catches any
// exception, drops the queue, resets the flag so the room still works,
// and `throw;` passes the same exception on to the caller.
void ChatRoom::enqueue(Message message) {
pending_.push_back(std::move(message));
if (delivering_) {
return; // the loop below, further up the call stack, will deliver it
}
delivering_ = true;
try {
while (!pending_.empty()) {
// Move the front message into a local and remove it from the
// queue before delivering, so a reply pushed during deliver
// goes behind it and the message being delivered stays put.
const Message next = std::move(pending_.front());
pending_.pop_front();
deliver(next);
}
} catch (...) {
pending_.clear(); // drop what was queued behind the failure
delivering_ = false;
throw;
}
delivering_ = false;
}
// One message to every present participant that wants() it, in joining
// order. `*this` passes this room to receive, so a bot can answer.
void ChatRoom::deliver(const Message& message) {
// join and leave are refused while delivering, so present_ cannot
// change during this loop.
for (const auto& reader : present_) {
if (wants(*reader, message)) {
reader->receive(message, *this);
}
}
}
How this code works: Delivering cai's !rules, step by step

In main.cpp, the room holds ana, ben, rulesbot, and cai, in that order, when room.post("cai", "!rules") runs. Call the question M1 and the bot’s answer M2.

Step What runs pending_ after delivering_ after
1 post checks cai, calls enqueue(M1) M1 true (it was false)
2 the loop takes M1, calls deliver(M1) empty true
3 ana and ben receive M1 empty true
4 rulesbot receives M1, calls room.post M2 true
5 cai is the sender, so wants says no M2 true
6 the loop takes M2, calls deliver(M2) empty true
7 ana, ben, and cai receive M2 empty true
8 the queue is empty, so the loop ends empty false
  1. Step 1. enqueue puts M1 in the queue. delivering_ is false, so this call becomes the one that runs the loop: it sets the flag.
  2. Step 4 is the interesting one. The bot’s post calls enqueue a second time, while the first call is still running further up the call stack. This second call finds delivering_ true, adds M2 to the back of the queue, and returns at once. Control goes back into the bot’s receive, then back into deliver(M1), which carries on with cai.
  3. Step 6. Only when M1 has reached everyone does the loop come round again and find M2. That is why ana and ben both see cai: !rules before rulesbot: be kind; no spam.
  4. Step 8. The outer enqueue clears the flag and returns, and so does post.

If any receive had thrown in steps 3 to 7, the catch (...) block would empty the queue (dropping M2, if it was waiting), clear the flag, and rethrow, so the exception reaches the code that called post.

The Observer page asked “what may change during a notification?”. The room has the same question, and answers it with three rules:

  • A message posted during a delivery waits in a queue. When the bot answers !rules inside its receive, the room is still in the middle of delivering the question. enqueue adds the answer to pending_ and returns; the loop that is already running delivers it after the question has reached everyone. We checked the alternative: in a scratch copy where a message posted during a delivery was delivered at once, a member who joined after the bot received the bot’s answer before the question, and the test for FR-5 failed.
  • Joining and leaving during a delivery are refused. deliver walks present_; adding or erasing an element in the middle of that loop would invalidate it, and leaving could destroy the very participant whose receive is running. join and leave throw std::logic_error instead. This is a deliberate limit; the exercise shows how to lift it.
  • A participant that throws stops the delivery. The exception reaches whoever called post, the messages queued behind it are dropped, and delivering_ is reset, so the room keeps working. Dropping is a choice: the queued messages were replies to a message that not everyone received.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

participants.hpp
// A person's chat window: it shows what the room delivers.
// It stores each delivered message as one line of text, ready to show.
class Member final : public Participant {
public:
// Passes the name on to the Participant part of the object.
explicit Member(std::string name) : Participant{std::move(name)} {}
void receive(const Message& message, ChatRoom& room) override;
const std::vector<std::string>& inbox() const { return inbox_; }
private:
std::vector<std::string> inbox_; // lines as shown on screen
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

participants.cpp
// Formats one delivered message as a screen line. The room has already
// decided that this member should see it, so there is nothing to check
// here except which kind of message it is. The ChatRoom parameter has no
// name because a member never answers; that also avoids an "unused
// parameter" warning.
void Member::receive(const Message& message, ChatRoom&) {
if (message.from.empty()) { // a notice from the room: "* ana joined"
inbox_.push_back("* " + message.text);
} else if (!message.to.empty()) { // a direct message, so it must be for us
inbox_.push_back(message.from + " (direct): " + message.text);
} else { // an ordinary post to everyone
inbox_.push_back(message.from + ": " + message.text);
}
}

Member knows nothing about the other participants, blocks, or direct messages for someone else; it never sees those. It decides only how a delivered message looks.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

participants.hpp
// Answers "!rules" in the room. It holds no pointer to the room: it
// answers through the room that delivered the message.
class RulesBot final : public Participant {
public:
RulesBot(std::string name, std::string rules)
: Participant{std::move(name)}, rules_{std::move(rules)} {}
void receive(const Message& message, ChatRoom& room) override;
int answered() const { return answered_; } // how many "!rules" it answered
private:
std::string rules_;
int answered_ = 0;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

participants.cpp
// Ignores everything except the exact text "!rules", and answers that by
// posting the rules to the whole room, under its own name.
void RulesBot::receive(const Message& message, ChatRoom& room) {
if (message.text == "!rules") {
++answered_;
// Posting from inside receive: the room queues this reply and
// delivers it after everyone has seen the question.
room.post(name(), rules_);
}
}

The bot answers through the room it was given. It does not know who will see the answer; if a member has blocked the bot, the room’s rule already covers that.

Keeping the mediator from becoming a god class

Section titled “Keeping the mediator from becoming a god class”

A mediator collects the rules that used to be spread over the colleagues, which is the point, and also the risk: it is the natural place to put everything. Signs that a mediator has become a god class:

  • It has a function per colleague type (deliver_to_member, deliver_to_bot), or it checks a colleague’s concrete type.
  • It does the colleagues’ own work: formatting lines, deciding what a bot says, storing a window’s scroll position.
  • Every new feature, even one that involves a single colleague, changes the mediator.
  • Its private data covers several unrelated concerns (who is present, message history, user settings, network connections).

This room avoids them by keeping to one job, who receives what:

Concern Where it lives here Why not in the room
how a message looks on screen Member::receive only the window cares
what the bot answers RulesBot::receive the bot’s own behaviour
who sent a message (identity) the app, outside the room trusts the name it is given (see below)
message history not built it would be its own class, fed by the room

When the rules themselves grow (muting, slow mode, moderators, keyword filters), the next step is to move wants into its own class, for example a DeliveryRules object that the room owns and asks. The room then keeps the membership and the queue, and the rules can be tested without participants. Until there are several rules, one private function is simpler, and splitting early would be a pattern for its own sake. Cohesion and coupling and the single responsibility principle give the general test: one reason to change per class.

Object Owner Lives
the room main (the app) as long as the app needs the room
a participant the room, through std::unique_ptr from join until leave, or until the room is destroyed
a reference from join_new nobody: a plain reference valid only while that participant is in the room
the room, seen from a participant nobody: a reference argument to receive valid for that call
a pending message the room’s queue until it is delivered, or dropped after an exception

The one rule the caller must keep is in the comment on join: a reference to a participant is valid until that participant leaves. In main, the reference cai is used for the last time just before room.leave("cai"). Because participants never hold a pointer to the room or to each other, there are no other references to go stale: when the room is destroyed, it destroys its participants, and nothing points back at them.

cai asks for the rules: everyone sees the question, then the bot's answer, which waited in the queue
Text description of the diagram

Main asks the ChatRoom to post “!rules” from cai. The room queues the question and starts delivering. It calls receive with the question on ana, ben, and rulesbot; cai is the sender, so cai does not receive it. Inside its receive, rulesbot posts the rules through the room. The room is already delivering, so it queues the answer. When the question has reached everyone, the room delivers the answer to ana, ben, and cai; rulesbot is its sender, so it does not receive it. Then post returns to main.

Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant R as ChatRoom
participant A as ana
participant B as ben
participant T as rulesbot
participant C as cai
M->>R: post(cai, !rules)
R->>R: queue the question, start delivering
R->>A: receive(question)
R->>B: receive(question)
R->>T: receive(question)
T->>R: post(rulesbot, rules)
R->>R: delivering, so queue the answer
R->>A: receive(answer)
R->>B: receive(answer)
R->>C: receive(answer)
R-->>M: returns

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// The room owns everyone; ana, ben, and cai are references to the
// Members inside it. The bot's reference is not needed, so it is not
// kept. Each join sends a "joined" notice to everyone present, the
// newcomer included (so cai's own list starts with "* cai joined").
ChatRoom room;
Member& ana = join_new<Member>(room, "ana");
Member& ben = join_new<Member>(room, "ben");
join_new<RulesBot>(room, "rulesbot", "be kind; no spam");
Member& cai = join_new<Member>(room, "cai");
// Everyone talks through the room, by name. The bot answers "!rules";
// its answer is queued and reaches everyone after the question.
room.post("ana", "hi all");
room.post("cai", "!rules");
room.block("ben", "cai"); // ben stops receiving cai's messages from here on
room.post("cai", "anyone there?");
room.send("ana", "ben", "lunch?");
// dan never joined, so send throws instead of losing the message.
try {
room.send("ana", "dan", "hello");
} catch (const std::invalid_argument& error) {
std::cout << "error: " << error.what() << '\n';
}
show(cai);
room.leave("cai"); // cai is destroyed here; the reference is not used again
show(ana);
show(ben);
std::cout << "in the room: " << room.size() << '\n';
Expected output
error: no member named dan
cai sees:
* cai joined
ana: hi all
rulesbot: be kind; no spam
ana sees:
* ana joined
* ben joined
* rulesbot joined
* cai joined
cai: !rules
rulesbot: be kind; no spam
cai: anyone there?
* cai left
ben sees:
* ben joined
* rulesbot joined
* cai joined
ana: hi all
cai: !rules
rulesbot: be kind; no spam
ana (direct): lunch?
* cai left
in the room: 3

Read the output against the requirements:

  • Everyone sees every join notice from the moment they are present (FR-4); ana’s window ends with * cai left.
  • ana sees cai: !rules and then rulesbot: be kind; no spam, in that order (FR-5), and does not see their own hi all (FR-1).
  • ben blocked cai, so ben’s window has cai: !rules (sent before the block) but not cai: anyone there? (FR-3); ana, who did not block cai, sees it.
  • Only ben sees ana (direct): lunch? (FR-2), and sending to dan, who is not in the room, is an error rather than a lost message.

The tests check the same rules one at a time, plus the edge cases:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_room.cpp
// Most tests use Probe, a test-only participant defined above this
// excerpt. It records each message it receives as "from>text" in its
// `heard` list (room notices, with no sender, are skipped), and then runs
// its `action`, if one is set: a std::function, a variable that holds any
// callable, here a lambda that takes the room. That lets a test make a
// participant act in the middle of a delivery. joined(list), also defined
// above, turns a list into one string such as "ana>hi bot>be kind", so a
// failed check prints the whole list.
//
// static_assert is checked by the compiler: the file does not compile if
// the condition is false. These prove a Member can be neither copied nor
// moved, so the room's references always point at the one real object.
static_assert(!std::is_copy_constructible_v<Member>);
static_assert(!std::is_move_constructible_v<Member>);
// FR-1: a post goes to everyone present except the sender.
LLD_TEST(a_post_reaches_everyone_but_the_sender) {
ChatRoom room;
Probe& ana = join_new<Probe>(room, "ana");
Probe& ben = join_new<Probe>(room, "ben");
Probe& cai = join_new<Probe>(room, "cai");
room.post("ana", "hi");
LLD_CHECK(ana.heard.empty());
LLD_CHECK_EQ(joined(ben.heard), std::string{"ana>hi"});
LLD_CHECK_EQ(joined(cai.heard), std::string{"ana>hi"});
}
// FR-2: a direct message reaches cai only; neither ana nor ben hears it.
LLD_TEST(a_direct_message_reaches_only_its_recipient) {
ChatRoom room;
Probe& ana = join_new<Probe>(room, "ana");
Probe& ben = join_new<Probe>(room, "ben");
Probe& cai = join_new<Probe>(room, "cai");
room.send("ana", "cai", "psst");
LLD_CHECK(ana.heard.empty());
LLD_CHECK(ben.heard.empty());
LLD_CHECK_EQ(joined(cai.heard), std::string{"ana>psst"});
}
// FR-3: ben blocked ana, so ben hears neither ana's post nor even their
// direct message to ben, while cai still hears the post.
LLD_TEST(blocking_hides_one_sender_from_one_reader) {
ChatRoom room;
join_new<Probe>(room, "ana");
Probe& ben = join_new<Probe>(room, "ben");
Probe& cai = join_new<Probe>(room, "cai");
room.block("ben", "ana");
room.post("ana", "one");
room.send("ana", "ben", "two");
LLD_CHECK(ben.heard.empty());
LLD_CHECK_EQ(joined(cai.heard), std::string{"ana>one"});
}
// FR-5: `late` joined after the bot, so the room reaches it after the
// bot has already answered. The answer was queued, so `late` still hears
// the question first, then the answer. ana, the sender, hears only the
// answer.
LLD_TEST(everyone_sees_a_message_before_any_reply_to_it) {
ChatRoom room;
Probe& ana = join_new<Probe>(room, "ana");
const RulesBot& bot = join_new<RulesBot>(room, "bot", "be kind");
Probe& late = join_new<Probe>(room, "late"); // after the bot in the room
room.post("ana", "!rules");
LLD_CHECK_EQ(bot.answered(), 1);
LLD_CHECK_EQ(joined(ana.heard), std::string{"bot>be kind"});
LLD_CHECK_EQ(joined(late.heard), std::string{"ana>!rules bot>be kind"});
}
// After ana leaves, only ben is left in the room, and the name "ana" is
// unknown (post throws). A new participant may take the name "ana", and
// ben hears them: ben's old block on ana was removed on leaving.
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// an exception of that type.
LLD_TEST(leaving_removes_the_participant_and_its_blocks) {
ChatRoom room;
join_new<Probe>(room, "ana");
Probe& ben = join_new<Probe>(room, "ben");
room.block("ben", "ana");
room.leave("ana");
LLD_CHECK_EQ(room.size(), std::size_t{1});
LLD_CHECK_THROWS(room.post("ana", "still here?"), std::invalid_argument);
join_new<Probe>(room, "ana"); // a new participant who reuses the name
room.post("ana", "hello");
LLD_CHECK_EQ(joined(ben.heard), std::string{"ana>hello"});
}
// ben.name() is a reference into ben, who is destroyed by leave. leave takes
// its parameter by value, so it works on a copy and this is safe.
LLD_TEST(a_participant_can_be_removed_by_its_own_name) {
ChatRoom room;
Probe& ana = join_new<Probe>(room, "ana");
const Probe& ben = join_new<Probe>(room, "ben");
room.leave(ben.name()); // the name is copied before ben is destroyed
LLD_CHECK_EQ(room.size(), std::size_t{1});
LLD_CHECK(ana.heard.empty());
}
// Each bad call throws std::invalid_argument: no participant at all, an
// empty name, a name already present, and three uses of the unknown
// "dan". None of them changed the room: only ana is still there.
LLD_TEST(the_room_refuses_bad_participants_and_unknown_names) {
ChatRoom room;
join_new<Probe>(room, "ana");
LLD_CHECK_THROWS(room.join(nullptr), std::invalid_argument);
LLD_CHECK_THROWS(join_new<Probe>(room, ""), std::invalid_argument);
LLD_CHECK_THROWS(join_new<Probe>(room, "ana"), std::invalid_argument);
LLD_CHECK_THROWS(room.send("ana", "dan", "hi"), std::invalid_argument);
LLD_CHECK_THROWS(room.block("ana", "dan"), std::invalid_argument);
LLD_CHECK_THROWS(room.leave("dan"), std::invalid_argument);
LLD_CHECK_EQ(room.size(), std::size_t{1});
}
// ben tries to remove ana from inside their receive(). leave throws
// std::logic_error; it passes up through enqueue, which resets the room,
// and out of post. Setting action to nullptr empties the std::function.
// Then a normal post shows the room still works and nobody was removed.
LLD_TEST(membership_cannot_change_during_a_delivery) {
ChatRoom room;
Probe& ana = join_new<Probe>(room, "ana");
Probe& ben = join_new<Probe>(room, "ben");
ben.action = [](ChatRoom& r) { r.leave("ana"); };
LLD_CHECK_THROWS(room.post("ana", "hi"), std::logic_error);
ben.action = nullptr;
LLD_CHECK_EQ(room.size(), std::size_t{2});
room.post("ben", "still working"); // the room recovered
LLD_CHECK_EQ(joined(ana.heard), std::string{"ben>still working"});
}
// Order in the room: ana, bot, thrower. ana posts "!rules": the bot
// queues its answer, then thrower throws. The exception reaches post's
// caller, and the queued answer is dropped, so ana never hears it. The
// room still delivers the next message.
LLD_TEST(a_throwing_participant_drops_the_queued_replies) {
ChatRoom room;
Probe& ana = join_new<Probe>(room, "ana");
join_new<RulesBot>(room, "bot", "be kind");
Probe& thrower = join_new<Probe>(room, "thrower");
thrower.action = [](ChatRoom&) { throw std::runtime_error{"boom"}; };
LLD_CHECK_THROWS(room.post("ana", "!rules"), std::runtime_error);
thrower.action = nullptr;
LLD_CHECK(ana.heard.empty()); // the bot's queued reply was dropped
room.post("thrower", "sorry");
LLD_CHECK_EQ(joined(ana.heard), std::string{"thrower>sorry"});
}

Pass the room to each call, or store it in each participant? We pass it. A stored ChatRoom& would let a member post on its own initiative (ana.post("hi")), which reads naturally, but it has two real costs. The reference would dangle if the ChatRoom object were moved (it is movable: its members are a vector, a set, a deque, and a flag). And a participant could call the room when the room does not expect it, for example from its destructor while leave or the room’s own destructor is running. Passing the room keeps the ownership one-way: the room owns the participants, and nothing points back. If your colleagues must act on their own (a timer in a bot, say), store a reference and document that the room outlives them, or give the bot a small handle from the room.

Names or references in the room’s API? post("ana", ...) finds the sender by name, which keeps the API simple and the tests readable. It also means the room trusts whoever calls it: anyone with the room can post as anyone. In a real app, the connection or session that belongs to a user would call the room, so the name comes from a trusted place. That check belongs to the app, not to the mediator.

Queue, or deliver at once? The queue is what makes FR-5 true, as the scratch experiment above showed. It also stops a chain of bots answering each other from growing the call stack without limit, though two bots that always answer each other would still keep the queue busy forever. Deliver at once only if colleagues never post from inside receive.

Refuse, or defer, changes to membership during a delivery? Refusing is simple and safe. Deferring (recording the change and applying it when the queue is empty) is what Observer’s feed does with cancelled subscriptions, and it is needed as soon as a colleague must make someone leave, as a moderator does. The exercise builds it.

Use Mediator when:

  • several peers must coordinate, and the rules involve more than one of them at once;
  • the set of peers changes while the program runs;
  • the same coordination rule would otherwise be copied into each peer;
  • you want to test the rules in one place, and each peer on its own.
  • One more class, and an indirection for every interaction: a reader must look in the mediator to see what a call to post does.
  • The mediator is a single point of change for every rule. That is the goal while the rules are about coordination; it becomes a cost when unrelated work collects there.
  • Colleagues depend on the mediator’s interface, so changing it changes them all. Keep it small.
  • A god mediator. The room that also formats messages, stores history, checks passwords, and runs bots. Each colleague becomes a thin shell, and the mediator becomes the whole program.
  • A mediator for two objects. If only two objects interact, a direct call is clearer.
  • A mediator that only forwards. If the mediator’s functions only pass calls through without deciding anything, it adds indirection and no rules; colleagues might as well call each other, or an Observer might fit better.
  • Colleagues that still talk to each other behind the mediator’s back, for example a bot that keeps a pointer to a member. Then the rules are in two places again.
  • “Mute a member for an hour.” One more condition in wants, and a member of the room for the mute list. No colleague changes.
  • “Add a message archive for people who join later.” A new colleague, or a separate class the room feeds; see the exercise.
  • “Several rooms, and a member can be in more than one.” Each room is its own mediator. Because a participant is owned by one room, a person in two rooms is two participants (two windows) that share a user account outside the rooms. Ownership by one room is what makes this so.
  • “Messages arrive from the network, on another thread.” The room is single-threaded (NFR-1). Keep it that way: let the network thread put messages on a queue that the room’s thread reads, rather than adding locks to the room.

Exercise: Add a colleague

  1. Add an Archive participant that keeps every message posted to the whole room, so that people who join later could read the history. Which existing classes must change?
  2. Compliance now requires the archive to keep direct messages too. A teammate proposes adding this to wants: if (reader.name() == "archive") { return true; }. What is wrong with it, and what would you do instead?
  3. Add a Moderator bot that removes anyone who posts a banned word. Why does calling room.leave(message.from) inside its receive fail today, and how would you change the room to allow it?
Show the explained answer

1. No existing class changes; that is the point of the pattern.

class Archive final : public Participant {
public:
explicit Archive(std::string name) : Participant{std::move(name)} {}
// The room has already applied its rules; the archive keeps a copy of
// each message it is given (push_back copies the Message).
void receive(const Message& message, ChatRoom&) override {
if (!message.from.empty()) { // skip the room's own notices
kept_.push_back(message);
}
}
const std::vector<Message>& kept() const { return kept_; }
private:
std::vector<Message> kept_;
};

It joins like anyone else (join_new<Archive>(room, "archive")), and the room’s rules already decide what it sees: posts from everyone else, but no direct messages for other people.

2. The check names one particular colleague inside the mediator. That is the first step to a god mediator: the room now knows about a kind of participant, and the next special case will be added the same way. It is also a privacy bug: anyone who joins with the name archive reads every direct message. Make the special role explicit instead, outside the list of participants. For example, give the room a log it reports every message to:

// An interface for "something that is told about every message". The
// room holds a pointer to one; it does not own it.
class MessageLog {
public:
virtual ~MessageLog() = default;
virtual void record(const Message& message) = 0;
};
// In ChatRoom:
// // Declaring any constructor stops the compiler providing the
// // default one, so it is written out again:
// ChatRoom() = default; // must now be written out
// explicit ChatRoom(MessageLog& log) : log_{&log} {}
// MessageLog* log_ = nullptr; // a private member
// and deliver() starts with: if (log_) { log_->record(message); }

Now the room’s interface says, for anyone to read, that this room reports everything to a log, and only the code that builds the room can supply one. This is an Observer of the room with a single listener; the log must outlive the room.

3. leave is refused with std::logic_error because the room is in the middle of deliver: erasing from present_ would invalidate the loop, and the participant being removed might be the one whose receive is running. The fix is to defer the removal, the same idea as marking cancelled subscriptions in Observer:

// During a delivery, only remember the name; the removal happens once
// the delivery loop has finished. Otherwise, remove at once.
void ChatRoom::leave(std::string name) {
require(name);
if (delivering_) {
leaving_.insert(std::move(name)); // a std::set<std::string> member
return;
}
remove(name); // the old body of leave: erase, drop blocks, notice
}
// In wants(): nothing more goes to, or comes from, someone leaving.
// if (leaving_.contains(reader.name()) || leaving_.contains(message.from)) {
// return false;
// }
// At the end of enqueue(), after delivering_ = false. One name at a
// time, so the names still waiting stay filtered by wants():
// extract() takes the first name out of the set (as a "node handle");
// value() is the string inside, which std::move then takes over.
// while (!leaving_.empty()) {
// std::string name = std::move(leaving_.extract(leaving_.begin()).value());
// remove(name); // may deliver "x left", and so run enqueue again
// }
// In the catch in enqueue(), next to pending_.clear():
// leaving_.clear();

The removal now happens when the queue is empty, and the “left” notice is delivered as a normal message. Three details are easy to get wrong:

  • Take one name at a time. Emptying the whole set first (with std::exchange, say) would let participants still waiting to leave receive the first “left” notice, and a leave requested during that notice would be processed twice, sending two “left” notices.
  • Members before the moderator have already received the banned message when the moderator sees it; the from check stops it reaching those after the moderator.
  • Decide what an exception means. Without the leaving_.clear() in the catch, the names would stay in the set, and those participants would stay in the room receiving nothing (a direct message to them silently lost) until some later delivery finished. Clearing means the removal is lost, like the queued messages.

In our scratch run, a member who joined before the moderator received ben’s banned message, then the moderator’s “ben was removed”, then the “ben left” notice; a member who joined after the moderator received only the last two. Two leaves requested in one round, plus a repeated leave during the first notice, gave exactly one notice for each.

  • Observer: also removes direct links between objects, but in the other shape: a subject announces an event to whoever subscribed without deciding who should react, and each listener decides. A mediator takes requests from its colleagues and itself decides which colleagues are affected. The two also combine: many mediators subscribe to their colleagues’ events, and a mediator can itself be a subject, as the room is for the MessageLog in answer 2 above. See Observer, and Observer vs Mediator.
  • Command: a message in the queue is close to a command waiting to run; if messages need undo or replay, make them commands. See Command.
  • Facade: also one object in front of several, but a facade simplifies a subsystem for outside callers, and the parts behind it do not know it exists. A mediator’s colleagues know it and use it. See Facade.
  • Mediator moves the coordination between peers into one object; the peers (colleagues) know only that object, never each other.
  • Put a rule that involves two or more colleagues in the mediator; keep each colleague’s own work (how it looks, what it says) in the colleague. That split is what keeps the mediator from becoming a god class.
  • In C++, decide ownership first: here the room owns its participants through std::unique_ptr, and passes itself to each receive, so nothing points back at the room.
  • Decide what may happen during a delivery: here, posts are queued so everyone sees a message before any reply, membership changes are refused, and a throwing participant leaves the room usable.
  • Prefer direct links for two or three fixed objects, and split the mediator’s rules into their own class once there are many of them.