Observer pattern
Let one object announce changes to any number of listeners without knowing who they are. Java and Python code, push vs pull, leaks, exceptions, ordering, async and pub/sub.
On this page
The problem: who needs to know?
A weather station measures the temperature. A phone app, a billboard and a frost alarm all want to react when it changes. There are two obvious ways to build this, and both hurt.
Option 1: the station calls everyone directly.
public void setTemperature(double celsius) {
this.temperature = celsius;
phoneApp.show(celsius);
billboard.display(celsius);
frostAlarm.check(celsius);
// marketing wants a logger next month: edit this method again
}
The station now depends on every class that cares about it. Adding a logger, or removing the billboard, means editing and re-testing the station. In a real system this is the OrderService.placeOrder() that ends with fifteen lines calling email, inventory, analytics, loyalty points and fraud checks.
Option 2: everyone keeps asking. Each display asks the station every few seconds, "anything new?" This is polling.
Polling: most of the questions get the answer "no change"
- The weather station measures the temperature. A phone app, a billboard and a frost alarm all want to know when it changes. One way: each of them asks the station every few seconds, “anything new?” That’s called polling, and most answers are “no”.
Polling wastes work when nothing changes, and is still late when something does: with a 10-second poll, a frost warning arrives on average 5 seconds after the frost, up to 10. Polling faster cuts the delay but multiplies the wasted questions.
The idea: subscribe once, get told when it happens
The Observer pattern turns it around. Interested objects, the observers, register with the object that has the information, the subject. When its state changes, the subject loops over its list and calls each observer's update(). The subject knows only the Observer interface, never the concrete classes.
Observers subscribe; the subject notifies all of them
- The Observer pattern flips it around. Interested objects subscribe to the station, called the subject. When the temperature changes, the station calls notify(), which calls update() on every observer.
| Role | In this example | Responsibility |
|---|---|---|
| Subject | WeatherStation | Keeps a list of observers; offers subscribe / unsubscribe; notifies them on change |
| Observer (interface) | TemperatureObserver | The one method the subject calls: update(celsius) |
| Concrete observers | PhoneApp, FrostAlarm, a logger | Decide for themselves what to do with the news |
The result is loose coupling: the subject and its observers can change independently, and observers can join or leave while the program runs. Another name you will hear is publish/subscribe at the class level; the system-design version with a broker in the middle is compared with Observer later on this page.
Build it step by step
1. The observer interface: one method.
2. The subject: a list, subscribe (which returns a handle to unsubscribe), and a private notify loop. Two details already matter: it notifies only when the value actually changes, and one failing observer must not stop the others.
3. Concrete observers: each one small, holding its own state (the frost alarm remembers whether it is already ringing).
4. The client wires them together.
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
// One file for reading; to run it: javac Demo.java && java Demo
// 1. The observer interface
@FunctionalInterface
interface TemperatureObserver {
void update(double celsius);
}
// 2. The subject
final class WeatherStation {
// Copy-on-write: observers may subscribe or unsubscribe while we are notifying
private final List<TemperatureObserver> observers = new CopyOnWriteArrayList<>();
private double temperature = Double.NaN; // "no reading yet"
/** Returns a handle; call run() on it to unsubscribe. */
public Runnable subscribe(TemperatureObserver o) {
observers.add(o);
return () -> observers.remove(o);
}
public double temperature() { return temperature; }
public void setTemperature(double celsius) {
if (Double.compare(celsius, temperature) == 0) return; // only notify on change
temperature = celsius;
notifyObservers();
}
// Not called notify(): Object.notify() is final in Java and is about thread signalling.
private void notifyObservers() {
for (TemperatureObserver o : observers) {
try {
o.update(temperature);
} catch (RuntimeException e) {
System.err.println("observer failed: " + e); // isolate failures
}
}
}
}
// 3. Concrete observers
final class PhoneApp implements TemperatureObserver {
public void update(double celsius) { System.out.println("Phone: " + celsius + " °C"); }
}
final class FrostAlarm implements TemperatureObserver {
private final double threshold;
private boolean ringing;
public FrostAlarm(double threshold) { this.threshold = threshold; }
public void update(double celsius) {
if (celsius < threshold && !ringing) {
ringing = true;
System.out.println("FROST! Cover the plants.");
} else if (celsius >= threshold) {
ringing = false;
}
}
}
// 4. The client
public class Demo {
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
station.subscribe(new PhoneApp());
station.subscribe(new FrostAlarm(2.0));
Runnable stopLogging = station.subscribe(c -> System.out.println("log " + c)); // a lambda works too
station.setTemperature(12); // Phone: 12.0 °C, log 12.0
station.setTemperature(1); // Phone: 1.0 °C, FROST!, log 1.0
stopLogging.run(); // unsubscribe the logger
station.setTemperature(0); // Phone: 0.0 °C (alarm already ringing, logger gone)
}
}import logging
from abc import ABC, abstractmethod
from typing import Callable
# 1. The observer interface
class TemperatureObserver(ABC):
@abstractmethod
def update(self, celsius: float) -> None: ...
# 2. The subject
class WeatherStation:
def __init__(self):
self._observers: list[TemperatureObserver] = []
self._temperature: float | None = None # no reading yet
def subscribe(self, observer: TemperatureObserver) -> Callable[[], None]:
"""Returns a function; call it to unsubscribe."""
self._observers.append(observer)
def unsubscribe() -> None:
if observer in self._observers:
self._observers.remove(observer)
return unsubscribe
@property
def temperature(self) -> float | None:
return self._temperature
def set_temperature(self, celsius: float) -> None:
if celsius == self._temperature:
return # only notify on change
self._temperature = celsius
self._notify_observers()
def _notify_observers(self) -> None:
for observer in list(self._observers): # a copy: observers may unsubscribe mid-loop
try:
observer.update(self._temperature)
except Exception:
logging.exception("observer failed") # isolate failures
# 3. Concrete observers
class PhoneApp(TemperatureObserver):
def update(self, celsius: float) -> None:
print(f"Phone: {celsius} °C")
class FrostAlarm(TemperatureObserver):
def __init__(self, threshold: float):
self.threshold = threshold
self.ringing = False
def update(self, celsius: float) -> None:
if celsius < self.threshold and not self.ringing:
self.ringing = True
print("FROST! Cover the plants.")
elif celsius >= self.threshold:
self.ringing = False
class Logger(TemperatureObserver):
def update(self, celsius: float) -> None:
print(f"log {celsius}")
# 4. The client
station = WeatherStation()
station.subscribe(PhoneApp())
station.subscribe(FrostAlarm(2.0))
stop_logging = station.subscribe(Logger())
station.set_temperature(12) # Phone: 12 °C, log 12
station.set_temperature(1) # Phone: 1 °C, FROST!, log 1
stop_logging() # unsubscribe the logger
station.set_temperature(0) # Phone: 0 °C (alarm already ringing, logger gone)New listeners, no edits
A logger subscribes at run time; the station's code is unchanged
- That gives loose coupling. A new Logger can subscribe while the program runs, and the station’s code doesn’t change. Updates arrive the moment something happens, instead of whenever someone next asks.
The logger joined with one subscribe call. WeatherStation was not opened, and neither was any other observer. Compare that with Option 1, where every new reaction meant editing setTemperature.
Push or pull?
What does update() carry? There are two styles, and a common middle way.
| Style | update signature | Good at | Weak at |
|---|---|---|---|
| Push the data | update(double celsius) | Observers get exactly what changed; no call back to the subject | The interface fixes what is sent; adding humidity changes every observer |
| Pull from the subject | update(WeatherStation s), then s.temperature() | Observers read only what they need; the interface never changes | Observers depend on the subject's API; by the time they read, the value may have changed again |
| Event object | update(WeatherChanged e) with old, new, time | Stable interface; new fields don't break old observers; a snapshot, so it can't change under you | One more small class per kind of event |
For anything beyond a toy, prefer an immutable event object. Java's own PropertyChangeEvent (with old and new values) and every UI framework's Event follow this style. It matters most when notification is asynchronous: a pull observer running later on another thread reads whatever the value is then, not the change it was told about.
The details that bite
The basic loop is five lines. These are the questions that separate a working version from a correct one.
A failing observer
Without the try/catch, an exception thrown by the second observer stops the loop, so the third never hears about the change, and the exception bubbles up into setTemperature(), whose caller did nothing wrong. Isolate each call and log the failure. (Some frameworks deliberately let it propagate; know which yours does.)
Changing the list during notification
A one-shot alert that unsubscribes itself inside update() removes an element from the list being iterated. With a plain ArrayList in Java that throws ConcurrentModificationException; in Python it silently skips the next observer. Iterate over a snapshot (list(self._observers)), or use a copy-on-write list, as above.
Order and re-entrancy
The pattern promises nothing about the order in which observers run. If the billboard must update after the database observer has saved, you have a hidden dependency: make it explicit (one observer that does both in order, or a pipeline) rather than relying on subscription order.
Re-entrancy is subtler: an observer that calls station.setTemperature() inside update() triggers a nested round of notifications before the first round has finished, so observers later in the outer loop are notified twice: once by the nested round and again by the outer one (and if the loop had captured the value before iterating, they would even receive the old value after the new one). Two observers that update each other can loop forever. Guard against it: don't let observers modify the subject, or queue changes and notify after the current round ends.
Synchronous or asynchronous?
As written, notification is synchronous: setTemperature() returns only when every observer has finished. A 2-second SMS observer makes every temperature update take 2 seconds.
| Synchronous (default) | Asynchronous (executor / event loop) | |
|---|---|---|
| Caller waits for | Every observer | Nothing; returns at once |
| Order | Deterministic within a round | Not guaranteed; observers may run in parallel |
| Exceptions | Visible to the subject (catch them) | Lost unless the executor logs them |
| Thread safety | Observers run on the caller's thread | Observers run on other threads; shared state needs locks |
| If the process dies | Half the observers ran | Queued notifications are lost |
Going async in-process (for example, submitting each update to an ExecutorService) fixes slowness but not durability. If a notification must not be lost, it doesn't belong in memory at all: write it to a durable queue or use the outbox pattern, which is where Observer turns into pub/sub.
Where this breaks
addEventListener is an observer; always pair it with an unsubscribe
- You use observers daily: button.addEventListener("click", …) subscribes to a button. Watch out for one trap: observers that never unsubscribe keep living in the list, a common memory leak. The system design version of this idea, with a broker in between, is pub/sub.
import java.lang.ref.WeakReference;
// Inside WeakWeatherStation: the list holds weak references
private final List<WeakReference<TemperatureObserver>> observers = new CopyOnWriteArrayList<>();
public void subscribe(TemperatureObserver o) { observers.add(new WeakReference<>(o)); }
private void notifyObservers() {
for (WeakReference<TemperatureObserver> ref : observers) {
TemperatureObserver o = ref.get();
if (o == null) observers.remove(ref); // collected: clean up the dead entry
else o.update(temperature);
}
}
// Trap: station.subscribe(c -> screen.show(c)). If nothing else holds that lambda,
// it can be collected and stop firing at any time.import weakref
class WeakWeatherStation:
def __init__(self):
self._observers = weakref.WeakSet() # entries vanish when the observer is collected
self._temperature = None
def subscribe(self, observer) -> None:
self._observers.add(observer)
def set_temperature(self, celsius: float) -> None:
self._temperature = celsius
for observer in list(self._observers):
observer.update(celsius)
# Trap: station.subscribe(Screen()) with no other reference to the Screen.
# In CPython the object is freed at once and never receives an update.
# For bound methods use weakref.WeakMethod(obj.method), not a plain weak reference.Lightweight forms
You rarely write the interface by hand today:
- Java: any functional interface takes a lambda (
Consumer<Double>).PropertyChangeSupportgives you a ready-made subject with old/new values.java.util.Observableexists but is deprecated since Java 9; don't use it. For streams of events with backpressure (a slow observer telling the subject to slow down), usejava.util.concurrent.Flow, RxJava or Reactor. - Python: store plain callables (
list[Callable[[float], None]]); any function or bound method is an observer. - JavaScript:
EventTarget.addEventListenerin browsers,EventEmitterin Node.js. - Frameworks: Spring
@EventListener, Django signals (post_save.connect(handler)), C#event, KotlinFlow, and the reactive state in Vue, MobX and Svelte.
Observer, pub/sub, mediator: how they differ
| Observer | Pub/sub (message broker) | Mediator | |
|---|---|---|---|
| Who knows whom | Subject holds direct references to its observers | Neither side knows the other; both know a topic on a broker | Colleagues know only the mediator |
| Where | One process, in memory | Across services and machines (Kafka, SNS, Redis pub/sub, Google Pub/Sub) | One process |
| Delivery | A method call, usually synchronous | Asynchronous; durable if the broker stores messages | Method calls |
| If a listener is down | It misses the event | A durable subscription catches up later | Not applicable |
| Use when | Objects in one program react to another object's changes | Services react to events and must scale or survive failures independently | Many objects interact in tangled ways and you want the rules in one place |
An in-process event bus (Guava EventBus, Spring events) sits in between: observers subscribe to an event type instead of a specific subject, which decouples publishers from subscribers inside one program. See pub/sub and events for the distributed version, and Command for when you want to store the request itself rather than broadcast that something happened.
When not to use it
In the interview
Users set alerts like "tell me once when AAPL goes above 200". Many users watch the same stock, and an alert removes itself after firing. Sketch the classes and the notify loop, and say what goes wrong with a naive ArrayList loop.
Compare with our answer
interface PriceObserver { void onPrice(String symbol, double price); }
final class Ticker {
private final Map<String, List<PriceObserver>> bySymbol = new ConcurrentHashMap<>();
public void subscribe(String symbol, PriceObserver o) {
bySymbol.computeIfAbsent(symbol, s -> new CopyOnWriteArrayList<>()).add(o);
}
public void unsubscribe(String symbol, PriceObserver o) {
List<PriceObserver> list = bySymbol.get(symbol);
if (list != null) list.remove(o);
}
public void publish(String symbol, double price) {
for (PriceObserver o : bySymbol.getOrDefault(symbol, List.of())) { // snapshot iteration
try { o.onPrice(symbol, price); }
catch (RuntimeException e) { System.err.println("alert failed: " + e); }
}
}
}
final class AboveAlert implements PriceObserver {
private final Ticker ticker; private final String user; private final double limit;
public AboveAlert(Ticker ticker, String user, double limit) {
this.ticker = ticker; this.user = user; this.limit = limit;
}
public void onPrice(String symbol, double price) {
if (price > limit) {
System.out.println("Tell " + user + ": " + symbol + " is " + price);
ticker.unsubscribe(symbol, this); // one-shot: safe with copy-on-write
}
}
}
// Client
Ticker t = new Ticker();
t.subscribe("AAPL", new AboveAlert(t, "priya", 200));
t.publish("AAPL", 199.5); // nothing
t.publish("AAPL", 201.0); // Tell priya: AAPL is 201.0, then the alert removes itself
t.publish("AAPL", 205.0); // nothingimport logging
from collections import defaultdict
class Ticker:
def __init__(self):
self._by_symbol: dict[str, list] = defaultdict(list)
def subscribe(self, symbol: str, observer) -> None:
self._by_symbol[symbol].append(observer)
def unsubscribe(self, symbol: str, observer) -> None:
if observer in self._by_symbol[symbol]:
self._by_symbol[symbol].remove(observer)
def publish(self, symbol: str, price: float) -> None:
for observer in list(self._by_symbol[symbol]): # snapshot: alerts remove themselves
try:
observer.on_price(symbol, price)
except Exception:
logging.exception("alert failed")
class AboveAlert:
def __init__(self, ticker: Ticker, user: str, limit: float):
self.ticker, self.user, self.limit = ticker, user, limit
def on_price(self, symbol: str, price: float) -> None:
if price > self.limit:
print(f"Tell {self.user}: {symbol} is {price}")
self.ticker.unsubscribe(symbol, self) # one-shot
t = Ticker()
t.subscribe("AAPL", AboveAlert(t, "priya", 200))
t.publish("AAPL", 199.5) # nothing
t.publish("AAPL", 201.0) # Tell priya: AAPL is 201.0
t.publish("AAPL", 205.0) # nothingWith a plain ArrayList and a for-each loop, the alert removing itself throws ConcurrentModificationException in Java; in Python, removing from the list being iterated skips the next alert. At scale, with a million alerts on one symbol, you would not loop over them all: keep alerts in a sorted structure by threshold and fire only those the price has crossed.
A strong answer mentions: observers grouped by symbol, so a price only reaches its own watchers · one-shot unsubscribe inside the callback · safe iteration (snapshot or copy-on-write) · one failing alert isolated from the others · a sorted index by threshold when there are many alerts per symbol.
- Intent: one subject, many observers; when the subject changes it calls
update()on each, knowing only the interface. - Beats polling: no wasted questions, no delay; beats direct calls: the subject doesn't depend on its listeners.
- Push vs pull: push data, or let observers read the subject; prefer an immutable event object with old and new values.
- Correct notify loop: iterate a snapshot or copy-on-write list · catch and log each observer's exception · notify only on real change · beware re-entrant updates.
- Order is not guaranteed; don't let observers depend on each other.
- Sync by default: a slow observer slows the subject. Async fixes speed, not durability.
- Lapsed listener leak: always unsubscribe on a lifecycle hook; weak references help but can drop inline lambdas.
- Don't notify inside an uncommitted transaction: after-commit listeners or an outbox.
- In-process Observer → event bus → pub/sub broker as listeners move to other services and must survive crashes.
placeOrder() notifies four in-process observers: email, SMS, analytics and loyalty points. Two problems appear in production: the SMS provider sometimes takes 3 seconds, making checkout slow, and last week an analytics bug threw an exception that stopped the loyalty observer from running for a whole day. Then the business says: "loyalty points must never be lost, even if a server crashes." What do you change?
Compare with our answer
- Isolate failures now: wrap each observer call in its own
try/catchand log, so one bug cannot block the others. - Make slow observers asynchronous: hand SMS and email to an executor or a job queue, so checkout returns without waiting.
- Notify after commit: run the listeners only after the order transaction succeeds, so nobody acts on a rolled-back order.
- Durability for loyalty: in-memory observers cannot promise "never lost". Write an
OrderPlacedrow to an outbox table in the same transaction as the order, and have a relay publish it to a broker (Kafka, SQS); the loyalty service consumes it and is idempotent (keyed by order ID), because delivery is at-least-once. - Monitor it: alert on outbox lag and on consumer errors.
A strong answer mentions: per-observer exception isolation · async for slow observers · after-commit notification · an outbox plus broker for must-not-lose events · idempotent consumers · monitoring of the backlog.
1. OrderService.placeOrder() ends with direct calls to email, inventory, analytics and fraud checks, and a new reaction is requested almost every month. Which change fits best?
The list of reactions keeps growing and OrderService shouldn't depend on any of them: an observer (event and listeners). A helper still has to be edited for each reaction, polling adds delay and wasted queries, and inheritance can't combine several reactions.
2. A trading app's dashboard screen subscribes to a price feed when it opens. After users open and close it a few hundred times, memory keeps growing and closed screens still log price updates. What is the most likely cause and fix?
This is the lapsed listener problem: the subject's list keeps closed observers reachable, so they can't be collected and keep receiving events. Unsubscribing on a lifecycle hook fixes it; forcing a garbage collection can't free objects that are still referenced.
3. A subject notifies five observers in a for-each loop. The second one throws a NullPointerException, and users report that the fourth observer's emails stopped going out. What is the best fix in the subject?
An uncaught exception ends the loop, so observers after the failing one never run. Isolating each call keeps the others working. Re-running the loop notifies early observers twice, sorting only hides the problem, and silently dropping observers loses features.
4. A one-shot alert calls ticker.unsubscribe(this) from inside its update(). In Java, with observers stored in an ArrayList, this throws ConcurrentModificationException. Which fix is correct?
The exception comes from modifying the list being iterated on the same thread, so locking doesn't help. Iterating a copy (or a copy-on-write list) lets observers remove themselves safely. Catching the exception inside update() doesn't help, because it is thrown by the iterator in the notify loop on its next step, and ArrayList.forEach also throws on modification.
5. A listener sends a confirmation email when OrderPlaced is published inside the order's database transaction. Sometimes payment fails, the transaction rolls back, and the customer has already been emailed. What should change?
The listener ran before the change was final. An after-commit listener (Spring's @TransactionalEventListener) or an outbox ties the side effect to a successful commit. Running it on another thread a bit later still races the rollback, and retries don't fix acting on an order that never existed.
6. A PriceSubject notifies observers on a thread pool. Each observer is passed the subject and calls subject.price() when it runs. Some alerts report a price different from the one that triggered them. What is the best fix?
With pull plus async delivery, observers read whatever the price is when they run, which may be a later update. Passing a snapshot (an immutable event) delivers the change they were told about. Synchronising price() makes each read consistent but still returns the newer value.
7. A shop's order service runs on 20 servers. The recommendation service, run by another team, needs every order event, and must catch up on anything it missed during its deploys. Which design fits?
Separate services, separate deploys and "catch up on what you missed" call for pub/sub with a durable broker (Kafka, SNS with SQS). An in-process observer or event bus only works inside one program and loses events while the listener is down; polling an API is the slow, wasteful alternative.
8. A team switches their subject to hold observers through weak references to stop leaks. Now some handlers, registered as subject.subscribe(e -> screen.refresh(e)), stop firing after a few minutes. Why?
A weak reference doesn't keep its target alive. A capturing lambda that nothing else holds is garbage, and is collected at the next suitable GC; then it silently stops firing. Keep a strong reference in the owner (the screen), or use explicit unsubscription instead.
Score 60% or more and the lesson is marked complete.