Observer

Lets objects subscribe to another object's events, and get notified automatically when something happens.

Why it matters

When one event must trigger several reactions, the code that raises the event ends up calling every reacting component directly, so adding a new reaction means editing it.

The idea

When an order is placed, email, analytics and stock might all need to react. Instead of the order code calling each one, they subscribe; the order publishes 'order placed', and every subscriber is notified. It's the in-program version of publish/subscribe.

Subscribing to a YouTube channel: when a new video is published, every subscriber is told, and the channel doesn't need to know who they are.

YouTube handles millions of subscribers reliably. A simple in-memory list of observers is lost if the program crashes, and one slow subscriber can slow the publisher. Across services, you'd use a message broker instead.

How it works

  1. The subject keeps a list of subscribers.
  2. Components that care call subscribe(callback).
  3. When the event happens, the subject loops through the list and calls each callback with the event's details.
  4. New reactions subscribe themselves; the subject never changes.
  5. Subscribers can unsubscribe when they no longer care.

Example

Button click listeners in user interfaces, stock-price updates, event systems.

Key points

Common mistakes

Not true: Observers are called in the order in which they subscribed, and code can rely on that.
In fact: The pattern promises no order, and a design that depends on one is fragile. If the order matters, make it explicit.

In the interview

Observer lets listeners subscribe to an object's events, so the publisher notifies all of them without knowing who they are — like 'order placed' triggering an email and a stock update. Across services I'd use the same idea with a message broker, for durability.

Part of Unit 6: Design patterns in the free System Design course.