What is the difference between the Observer pattern and Publish-Subscribe?
In Observer, observers register directly with the subject and the subject calls them. In Pub-Sub, a message broker sits between publishers and subscribers, so neither knows the other.
Explain it simply
Observer is like telling the shopkeeper directly, "call me when the new phone arrives". Pub-Sub is like a notice board service: shops post news under a topic, and customers who follow the topic get it. The shop never learns who customers are.
Example
Observer:
Subject --notifies--> Observer A
--notifies--> Observer B (subject holds the list, same process)
Pub-Sub:
Publisher --> [ Broker / topic "orders" ] --> Subscriber A
--> Subscriber B
(publisher and subscribers do not know each other)// A tiny pub-sub broker
const topics = {};
const subscribe = (topic, fn) => (topics[topic] ||= []).push(fn);
const publish = (topic, msg) => (topics[topic] || []).forEach((fn) => fn(msg));
subscribe("orders", (m) => console.log("Billing got " + m));
publish("orders", "order#7"); // Billing got order#7Pub-Sub scales across processes and machines (Kafka, RabbitMQ, Redis), while classic Observer is usually in-memory in a single program.
What to say in the interview
"Observer has direct subject-to-observer links, usually in one process. Pub-Sub adds a broker, so publishers and subscribers are fully decoupled by topic and can even run on different machines. The price of Pub-Sub is extra infrastructure and harder debugging."
Common mistakes
- Treating the two as exact synonyms.