Skip to content

Observer vs Mediator

Difficulty: Intermediate

Prerequisites

Key concepts

  • observer pattern
  • mediator pattern
  • event bus
  • coupling
  • choosing a pattern
  • Why Observer and Mediator are confused: both put one object between others so that they do not hold links to each other.
  • The difference that matters: a subject broadcasts a change and does not decide who reacts; a mediator coordinates, and decides.
  • How the two examples differ in ownership and in what happens when a reaction causes another event.
  • How the two combine, and why a global event bus is usually neither.
  • Observer: one object changes, and whoever cares is told. The PriceFeed publishes each price to every subscribed listener, in order, and does not know what any of them does. The listeners decide what a price means to them: the board shows it, the log keeps it, the alert checks it against a limit. Knowledge points one way, at most: the feed knows only “something that has on_price”, and a listener need not know the feed at all. main subscribes the board and the log; only the alert takes the feed, to hold its own subscription.
  • Mediator: several objects interact, and one object holds the rules of how. A chat participant never sends a message to another participant. It posts to the ChatRoom, and the room decides who receives it: not the sender, not someone who blocked the sender, only the named reader of a direct message. The room knows every participant; each participant knows only the room.

So the question is where the decision lives. In Observer, each receiver decides for itself, and the sender does not care who receives. In Mediator, the decision about who is affected is the mediator’s job, and it is written in one place.

The interface each receiver implements, and the object in the middle:

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

price_listener.hpp
// Anything that wants to hear about price changes: the observer interface.
// The feed only knows this type, never PriceBoard or TradeLog, so a new
// kind of listener needs no change to the feed.
class PriceListener {
public:
// Virtual, so destroying a listener through a PriceListener pointer or
// reference runs the destructor of the real (derived) class too.
virtual ~PriceListener() = default;
// `= 0` makes this pure virtual: PriceListener has no body for it, and
// every concrete listener must write its own (marked `override`). The
// feed calls it once per update; the listener decides what it means.
virtual void on_price(const PriceUpdate& update) = 0;
// The feed knows each listener by its address, so a listener is never
// copied or moved: a copy would have a different address.
PriceListener(const PriceListener&) = delete;
PriceListener& operator=(const PriceListener&) = delete;
protected:
// Protected: only a derived class can construct a PriceListener, so
// nobody can try to make a bare "listener of nothing".
PriceListener() = default;
};

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_;
};
How this code works: Reading the two interfaces side by side

The two classes look alike: each has a virtual destructor, one pure virtual function (= 0) that every receiver must write, and deleted copy operations, so each receiver is one object at one address. The differences are in what each function is given, and they say how much each receiver knows.

  1. What the call carries. on_price gets only the update. A listener is not told which feed called it. A listener that needs the feed must be given it some other way, as DropAlert is: it takes the feed in its constructor, only to subscribe, and afterwards uses its own Subscription handle. receive gets the message and the room, so any participant can answer through the room, as the rules bot does with room.post, without keeping a pointer to the room or to any other participant.
  2. Who has a name. A Participant has a name(), because the room’s rules need it: wants compares the reader’s name with the message’s sender and recipient, and looks it up in the blocks. A PriceListener has no name, because the feed never tells listeners apart: it calls all of them.
  3. Who owns the receiver. The feed stores plain pointers to listeners that someone else owns, so the rule “the listener must outlive its subscription” is the caller’s job. The room takes each participant as a std::unique_ptr in join and destroys it in leave, so a participant cannot outlive its place in the room.

class PriceFeed final

the subject; not copyable

Data members

  • std::shared_ptr<ListenerList> listeners_; never null; entries point at listeners it does not own

Member functions

  • Subscription subscribe(PriceListener& listener); the listener must outlive the handle
  • void publish(const PriceUpdate& update); every subscribed listener, in subscription order
  • std::size_t listener_count() const;

interface (abstract class) PriceListener

the observer; not copyable, so its address is stable

Member functions

  • virtual void on_price(const PriceUpdate& update) = 0; the listener decides what to do
Observer: the feed keeps a list of listeners it does not own, and tells all of them

class ChatRoom final

the mediator

Data members

  • std::vector<std::unique_ptr<Participant>> present_; owned; in joining order
  • std::set<std::pair<std::string, std::string>> blocks_; (who, blocked): a rule's data
  • std::deque<Message> pending_; posted, not yet delivered
  • bool delivering_; true while a message is being delivered
  • bool wants(const Participant& reader, const Message& message) const; private: every delivery rule
  • void enqueue(Message message); private: queues, and delivers unless already delivering

Member functions

  • Participant& join(std::unique_ptr<Participant> participant); takes ownership
  • void leave(std::string name); destroys that participant
  • 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);
  • void block(const std::string& who, const std::string& blocked);

interface (abstract class) Participant

a colleague; knows only the room

Member functions

  • virtual void receive(const Message& message, ChatRoom& room) = 0;
Mediator: the room owns its participants and decides who receives each message

The room’s public functions check their arguments, then queue a message or record a block. Every rule about who receives a message is in one private function, wants:

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});
}

PriceFeed has no such function. It has nothing to decide: every subscriber gets every update.

Observer: the feed tells every listener; each decides on its own what the price means
Text description of the diagram

A sequence diagram with five participants: main, the PriceFeed, a PriceBoard, a TradeLog, and a DropAlert. main calls publish on the feed with ACME at 99.50. The feed calls on_price on the board, which remembers the latest price; then on the log, which adds a line; then on the alert, which sees that the price is below 100.00, records a message, and cancels its own subscription, which only marks its entry in the feed’s list. When the round ends, the feed removes the marked entry, and publish returns to main. The feed made no decision about who should react: it called every listener, and each listener decided for itself.

Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant F as PriceFeed
participant B as PriceBoard
participant L as TradeLog
participant A as DropAlert
M->>F: publish(ACME 99.50)
F->>B: on_price(update)
B->>B: remember the latest price
F->>L: on_price(update)
L->>L: add a line
F->>A: on_price(update)
A->>A: below 100.00, so record a message
  A->>F: cancel its subscription (marks its entry)
F->>F: round ends, so remove the marked entry
F-->>M: publish returns
Mediator: the room decides who receives the question, and queues the bot's answer until everyone has seen it
Text description of the diagram

A sequence diagram with six participants: main, the ChatRoom, and the members ana, ben, rulesbot, and cai. main posts “!rules” to the room as cai. The room goes through the participants in joining order, and for each one asks its rules, wants, and delivers if the answer is yes. Ana, ben, and rulesbot receive the question. While receiving it, rulesbot posts its answer, “be kind; no spam”, to the room. The room is still delivering, so it queues the answer. Then it reaches cai, who does not receive the question, because it is cai’s own message. When the question has reached everyone, the room delivers the answer to ana, ben, and cai, but not to rulesbot, its sender. Then post returns to main. Every decision about who receives what was made by the room.

Diagram source (Mermaid)
sequenceDiagram
participant M as main
participant R as ChatRoom
participant Ana as ana
participant Ben as ben
participant Bot as rulesbot
participant Cai as cai
M->>R: post("cai", "!rules")
  Note over R: for each reader in joining order, wants? then receive
R->>Ana: receive(question, room)
R->>Ben: receive(question, room)
R->>Bot: receive(question, room)
Bot->>R: post("rulesbot", the rules)
  R->>R: delivering, so queue the answer
R->>R: cai no (own message), question done
R->>Ana: receive(answer, room)
R->>Ben: receive(answer, room)
R->>Cai: receive(answer, room)
R-->>M: post returns

Both diagrams have a reaction that calls back into the middle object while it is still working: the alert cancels its subscription, the bot posts an answer. Both examples had to decide what that means. The feed marks the alert’s entry and removes it after the round, so the round finishes safely. The room queues the answer, so that everyone sees the question before any reply to it. That decision is easy to miss with either pattern, and both examples test it.

Question Observer (PriceFeed) Mediator (ChatRoom)
Who decides who reacts? each listener, for itself; the feed tells everyone the mediator, in wants: sender, direct messages, blocks
What does the middle object know? only the listener interface every colleague by name, and the rules between them
Which way do messages flow? one way: from the subject to its listeners every way: any colleague to any other, through the room
Who owns the receivers? not the feed: listeners are owned elsewhere; handles unsubscribe the room, through std::unique_ptr, from join until leave, or until the room is destroyed
What does a new receiver cost? nothing in the feed: subscribe one more listener nothing in the room, unless it needs a new rule
What does a new rule cost? it lives in each listener that applies it, and nothing shows them together one change, in the mediator
Typical risk the subject cannot show who reacts to what; listener order dependencies the mediator grows into a god class
  1. Does the sender care who reacts? A price feed does not: it reports a fact. A chat message does: who must and must not receive it is part of its meaning. If the sender would be content with “everyone who subscribed”, it is Observer.
  2. Do the reactions depend on each other, or on rules about the receivers? “Do not deliver to someone who blocked the sender”, “enable OK only when every field is valid”, “only one of these panels can be open”. Rules that involve several participants at once belong in a mediator. If each reaction depends only on the event and the listener’s own data, Observer is enough.
  3. Does the middle object do more than forward? A subject that starts filtering (“only tell the alert about ACME”) and ordering (“the log must hear before the board”) is turning into a mediator, and should be designed as one, or the filtering should move into the listeners.
  • A mediator often uses Observer underneath. The colleagues are subjects: a text field announces “my text changed”, a checkbox “I was ticked”. The mediator subscribes to all of them, decides what each change means for the others, and calls them. Unlike plain Observer, only one object listens to the colleagues, and it knows the whole picture.
  • A mediator can be a subject. A chat room can report every message to a log interface, without knowing what the log does with it. Answer 2 of the Mediator exercise does this with a MessageLog.
  • A command fits either. An update or a message can become a Command object and wait in a queue, so that it can be handled later, on another thread, or undone.

An event bus is a single object, often global, where any code can publish any kind of event and any code can subscribe to any kind. It looks like a mediator, one hub that everyone talks to, but it holds no rules: it forwards every event to whoever subscribed to that type. In pattern terms it is Observer with every subject merged into one. That has costs that grow with the program:

  • Nobody can see the design. To learn what happens when an order is placed, you must search the whole program for subscribers to OrderPlaced, and then for what each of them publishes in turn. The coordination a mediator would hold in one class is spread across the subscribers, and invisible in any class diagram.
  • Order and cycles. Two handlers for one event run in subscription order, which usually depends on start-up order. A handler that publishes another event, which triggers a third handler, which publishes the first event again, is a loop that no single file shows.
  • Lifetime. A handler registered by an object that is later destroyed is the dangling-listener bug from the Observer page, now in a global object that outlives everything. Every subscription needs a handle, as Subscription is, and a global bus makes that easy to forget.
  • Types. A bus that carries every kind of event often stores payloads as std::any or behind a base class, and each handler casts back. A mistake in the event type is then found at run time, as a std::bad_any_cast or a failed dynamic_cast, or not at all: a handler subscribed to the wrong type simply never runs.
  • Synchronous or not? If publish calls handlers directly, a slow handler slows every publisher. If it queues them, the publisher can no longer assume anything has happened when publish returns. Either is fine, but every user of the bus must know which it is. A queued event must own its data: a reference or pointer to the publisher’s local variables dangles by the time the handler runs.
  • Two objects with a fixed relationship. If the price board is the only thing that will ever care about prices, the feed can call it. Observer pays off when the set of listeners changes or is unknown to the subject.
  • One callback. If there is exactly one receiver, chosen by the creator, a std::function member or parameter is smaller than a listener interface and a subscription list.
  • Colleagues that rarely interact. If two widgets have one rule between them, a direct call between them, or a small function in the dialog that owns them both, may be clearer than a mediator class.

Exercise: Pick a design for three user interfaces

For each interface, choose Observer, Mediator, both, or direct calls. Say which object decides who is affected, and who owns what.

  1. A “network settings” dialog has a Use proxy checkbox, proxy host and port fields, and an OK button. The host and port are enabled only while the box is ticked, and OK is enabled only when every enabled field is valid.
  2. A dashboard shows one temperature sensor’s reading in a chart, a numeric label, and an alarm icon. Plug-ins can add more views, and views come and go as the user rearranges the screen.
  3. A music player has a play/pause button, a progress bar, and a playlist. The player engine changes track at the end of a song; dragging the progress bar seeks; double-clicking the playlist plays another track.
Show the explained answer

1. A mediator: the dialog. The rules involve several widgets at once (“OK is enabled when every enabled field is valid”), so they belong in one place. The dialog owns its widgets; each widget reports its changes to the dialog, often through Observer-style callbacks that the dialog registers, and the dialog decides which other widgets change. No widget knows another.

2. Observer. The sensor reports a fact, the new reading, and does not care who shows it. Each view decides what to draw, and views are added and removed while the program runs, so each needs a subscription handle that it owns, which ends the subscription when the view is destroyed. The screen layout owns the views, plug-in views through std::unique_ptr; the sensor owns none of them. Each view declares its subscription as its last member, so the subscription ends before the rest of the view is destroyed. A mediator would add nothing, because there are no rules between the views.

3. Observer from the engine to the views, and direct calls from the views to the engine. The engine is the subject: the button, the bar, and the playlist each subscribe to the events they need (“track changed”, “position changed”, “playing or paused”) and redraw themselves. The player window owns the engine and the three views; each view holds a reference to the engine, so the engine must outlive them. User actions are plain calls on the engine: seek, play(track), toggle_pause. Neither direction needs a mediator, because the views never coordinate with each other; they only follow the engine. If rules between views appeared, such as “hide the progress bar while the playlist is being edited”, that would be the time to introduce one. Watch for the round trip: dragging the bar calls seek, and the engine’s “position changed” comes straight back to the bar while its own handler is running. The bar must expect that, for example by ignoring position updates while it is being dragged.