Observer
Intent
Defines a subscription mechanism that notifies multiple objects about events in the object they observe.
Problem
Customers keep polling the store for a new product, or the store spams everyone.
Solution
The publisher keeps a list of subscribers and notifies them when something happens. Events, signals and pub/sub are all Observer.
Real-world analogy
A magazine subscription: new issues arrive when they're published, so you don't keep checking the shop.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Publisher — Publisher issues events and keeps the subscription list.
- 2Publisher — When an event happens, it loops over subscribers and calls update().
- 3Subscriber — Subscriber declares the notification interface, usually a single update method.
- 4ConcreteSubscribers — Concrete Subscribers react to notifications.
- 5Client — Client creates publishers and subscribers and registers subscriptions.
Try it
Code example
template <typename Event>
class Subject {
public:
using Handler = std::function<void(const Event&)>;
void subscribe(Handler h) { handlers.push_back(std::move(h)); }
void notify(const Event& e) const {
for (const auto& h : handlers) h(e);
}
private:
std::vector<Handler> handlers;
};
// Subject<std::string> saved;
// saved.subscribe([](const std::string& name) { std::cout << "Saved " << name << '\n'; });
// saved.notify("report.txt");Applicability
Use Observer when changes in one object require changes in others, unknown in advance.
Use Observer when some objects should observe others only for a time.
How to implement
- Split business logic into a publisher and subscribers
- Declare the subscriber interface (often a callback type)
- Add subscribe / unsubscribe to the publisher
- Notify subscribers when the event happens
- Subscribers register with publishers
Pros and cons
Pros
- Open–Closed: new subscribers without changing the publisher
- Relationships set up at runtime
Cons
- Notification order is not guaranteed
- Forgotten subscriptions can leak memory
Relations with other patterns
Check yourself
When an order is paid, the email, inventory and analytics modules must react, and more may be added later.
Saved in this browser only. Part of Behavioral patterns (0/11), Hands-on: patterns with live demos (0/5).