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
- The subject keeps a list of subscribers.
- Components that care call subscribe(callback).
- When the event happens, the subject loops through the list and calls each callback with the event's details.
- New reactions subscribe themselves; the subject never changes.
- Subscribers can unsubscribe when they no longer care.
Example
Button click listeners in user interfaces, stock-price updates, event systems.
Key points
- Decouples the publisher from its listeners.
- Subscribers can be added and removed at runtime.
- Watch for memory leaks (forgotten subscribers) and slow or failing subscribers.
- At system level, the same idea becomes pub/sub with a message broker.
Common mistakes
- Never unsubscribing an observer: the subject keeps a reference to it, so it is never freed (a memory leak).
- Letting one subscriber's error stop the others from being notified.
- Relying on subscribers being called in a particular order.
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.