Algo-Sim › Design Patterns
Observer: publish and subscribe
Easy · Design Patterns · step through it in Java, Python and C++ on your own input
A subject keeps a list of observers and calls each one when its state changes, so new kinds of listeners can be added without touching the subject.
Problem
A newsletter keeps a list of subscribed readers. subscribe(r) and unsubscribe(r) change the list, and publish(value) delivers the value to every current subscriber and returns how many were notified. The newsletter must not depend on the concrete reader classes.
Constraints
- The subject only knows the observer interface
- publish is O(number of subscribers)
- Subscribing twice must not deliver twice
Edge cases to test
- An observer that unsubscribes while being notified
- No observers
- An observer that throws
Follow-up questions
- How do you avoid memory leaks?
- Always unsubscribe (or hold weak references), or the subject keeps dead listeners alive.
- What changes when observers are on other machines?
- Use a message broker (pub/sub): the publisher no longer waits, and delivery can be retried or ordered per topic.
Solution
Java
interface Subscriber {
void update(int value);
}
class Reader implements Subscriber {
final int id;
int last = -1;
Reader(int id) { this.id = id; }
public void update(int value) { last = value; }
}
class Channel {
private final List<Subscriber> subscribers = new ArrayList<>();
public void subscribe(Subscriber s) {
if (!subscribers.contains(s)) subscribers.add(s);
}
public void unsubscribe(Subscriber s) {
subscribers.remove(s);
}
public int publish(int value) {
for (Subscriber s : subscribers) s.update(value);
return subscribers.size();
}
}Python
class Reader:
def __init__(self, id):
self.id = id
self.last = -1
def update(self, value):
self.last = value
class Channel:
def __init__(self):
self.subscribers = []
def subscribe(self, s):
if s not in self.subscribers:
self.subscribers.append(s)
def unsubscribe(self, s):
if s in self.subscribers:
self.subscribers.remove(s)
def publish(self, value):
for s in self.subscribers:
s.update(value)
return len(self.subscribers)C++
#include <bits/stdc++.h>
using namespace std;
struct Subscriber {
virtual void update(int) = 0;
virtual ~Subscriber() = default;
};
struct Reader : Subscriber {
int id, last = -1;
explicit Reader(int id)
: id(id) {}
void update(int value) override {
last = value;
}
};
class Channel {
vector<Subscriber *> subscribers;
public:
// Subscribers are borrowed; their owner keeps them alive until they unsubscribe.
void subscribe(Subscriber *s) {
if (find(subscribers.begin(), subscribers.end(), s) == subscribers.end())
subscribers.push_back(s);
}
void unsubscribe(Subscriber *s) {
subscribers.erase(remove(subscribers.begin(), subscribers.end(), s), subscribers.end());
}
int publish(int value) {
for (auto *s : subscribers)
s->update(value);
return int(subscribers.size());
}
};
More Design Patterns problems
- Strategy: swappable discounts (Easy)
- State: a document workflow (Easy)
- Command: undo and redo (Medium)
- Chain of Responsibility: an ATM (Easy)
- Factory: create without naming classes (Easy)
- Singleton: one shared instance (Easy)
- Builder: a pizza step by step (Easy)
- Decorator: stack toppings at runtime (Easy)
- Adapter: two legacy sensors, one interface (Easy)
- Proxy: a caching, lazy price service (Easy)
- Composite: folder sizes (Easy)