100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Observer vs Pub/Sub Pattern

Observer vs Pub/Sub pattern -- direct notification vs broker-mediated decoupling -- explained with Java examples and interview questions.

mediumQ186 of 226 in Object Oriented Programming Est. time: 5 minsLast updated:
Open Code Lab
186 / 226

Expected Interview Answer

The Observer pattern is a direct, in-process relationship where a Subject holds references to its Observers and notifies them synchronously, while Publish/Subscribe decouples publishers and subscribers entirely through an intermediary broker or event channel, so neither side knows the other exists.

In classic Observer, the Subject maintains a list of Observer objects (often via attach/detach methods) and calls notify() to invoke each Observer’s update() method directly -- it is tightly coupled but simple, typically synchronous, and lives within a single process. In Pub/Sub, publishers emit events to a named topic or channel on a broker (in-process event bus, or an external system like a message queue), and subscribers register interest in that topic without any reference to the publisher; the broker handles routing, and delivery can be asynchronous, potentially across process or network boundaries. The key structural difference is the presence of a broker/topic layer: Observer is a two-party contract (Subject knows its Observers), whereas Pub/Sub is a three-party arrangement (Publisher, Broker, Subscriber) with no direct reference between publisher and subscriber, enabling much looser coupling and more scalable, distributed event delivery.

  • Observer: simple, synchronous, easy to reason about within one process
  • Pub/Sub: publishers and subscribers can be added/removed without touching each other
  • Pub/Sub scales naturally to distributed, cross-process, or cross-service messaging
  • Both support one-to-many notification without polling

AI Mentor Explanation

Observer is like a captain who personally keeps a list of every fielder’s phone number and calls each one directly when a field change is needed -- a tight, direct relationship where the captain knows exactly who is listening. Pub/Sub is like the team using a stadium PA announcement system: the captain just announces "field change" to the PA (the broker), and any fielder who has their earpiece tuned to that channel hears it, without the captain knowing or caring who exactly is listening. Adding a new fielder to the team doesn’t require the captain to update any personal call list in the Pub/Sub case.

Step-by-Step Explanation

  1. Step 1

    Observer: Subject maintains a list

    The Subject holds direct references to Observers via attach()/detach() methods.

  2. Step 2

    Observer: notify() calls each Observer directly

    The Subject synchronously invokes update() on every registered Observer.

  3. Step 3

    Pub/Sub: Publisher emits to a topic

    The Publisher sends an event to a named channel on a broker, with no reference to any subscriber.

  4. Step 4

    Pub/Sub: Broker routes to Subscribers

    The broker delivers the event to every Subscriber registered on that topic, potentially asynchronously.

What Interviewer Expects

  • Clear articulation of the broker/intermediary as the structural difference
  • Understanding that Observer is typically synchronous and in-process
  • Awareness that Pub/Sub enables cross-process or distributed messaging
  • Recognition that Pub/Sub decouples publisher and subscriber lifecycles entirely

Common Mistakes

  • Treating Observer and Pub/Sub as identical patterns with different names
  • Assuming Observer always requires an event bus or broker
  • Believing Pub/Sub is always asynchronous by definition rather than by common implementation
  • Ignoring that Observer's Subject-Observer relationship is direct while Pub/Sub is broker-mediated

Best Answer (HR Friendly)

Observer is when an object (the Subject) keeps a direct list of listeners and calls them itself when something changes -- both sides know about each other. Pub/Sub adds a middleman, a broker or event channel, so publishers just announce events to a topic and subscribers listen to that topic, with neither side needing a direct reference to the other. That makes Pub/Sub much better suited to loosely coupled or distributed systems, while Observer is simpler and fine for tightly related objects in the same process.

Code Example

Observer (direct) vs Pub/Sub (broker-mediated)
// --- Observer: Subject holds direct references ---
interface Observer { void update(String event); }

class Subject {
    private final List<Observer> observers = new ArrayList<>();
    void attach(Observer o) { observers.add(o); }
    void notifyAll(String event) {
        for (Observer o : observers) o.update(event); // direct call
    }
}

// --- Pub/Sub: broker decouples publisher and subscriber ---
class EventBus {
    private final Map<String, List<Observer>> topics = new HashMap<>();
    void subscribe(String topic, Observer o) {
        topics.computeIfAbsent(topic, t -> new ArrayList<>()).add(o);
    }
    void publish(String topic, String event) {
        for (Observer o : topics.getOrDefault(topic, List.of())) {
            o.update(event); // publisher never references subscribers directly
        }
    }
}

EventBus bus = new EventBus();
bus.subscribe("order.created", e -> System.out.println("Notify: " + e));
bus.publish("order.created", "Order #123"); // Publisher has no reference to the subscriber

Follow-up Questions

  • Why is Pub/Sub better suited to microservice architectures than the Observer pattern?
  • Can Pub/Sub be implemented purely in-process, without an external message broker?
  • What failure modes does asynchronous delivery introduce that synchronous Observer notification avoids?
  • How does topic-based routing in Pub/Sub differ from Observer's single notify() call?

MCQ Practice

1. What is the key structural difference between Observer and Pub/Sub?

Pub/Sub routes events through an intermediary broker so publishers and subscribers never reference each other directly.

2. In classic Observer, how does the Subject notify listeners?

The Subject holds direct references to Observers and invokes their update() method itself.

3. Which scenario most naturally favors Pub/Sub over Observer?

Pub/Sub's decoupling and broker-based routing scale naturally to distributed, cross-service event delivery.

Flash Cards

Observer in one line?Subject holds direct references to Observers and notifies them synchronously.

Pub/Sub in one line?Publisher and Subscriber are decoupled by a broker/topic; neither references the other.

Which is typically in-process only?Observer -- Pub/Sub commonly spans processes or services.

Key benefit of Pub/Sub?Publishers and subscribers can be added or removed independently, enabling loose coupling at scale.

1 / 4

Continue Learning