Define a one-to-many dependency so that when one object (the subject) changes state, all its registered dependents (observers) are notified automatically, without the subject depending on their concrete classes.
Observer lets one object announce that its state changed, while any number of other objects decide for themselves what to do about it. The announcing object keeps a list of subscribers and calls each one. It never needs to know what they are.
You already use it every time you write addEventListener, connect a signal, or register a callback. Interviewers like it because it looks trivial and isn't. Expect follow-up questions on notification order, what happens when a listener throws, synchronous versus asynchronous delivery, and the classic leak: a subscriber that is never removed stays alive as long as the subject does.
This guide builds one example from start to finish: a bike-share docking station that has to keep a rider map, a van dispatcher and an analytics log in sync.
The problem
A situation where the obvious design starts to hurt.
You work on Harbor Bikes, a bike-share network with 340 docking stations across a coastal city. Each station has a fixed number of docks, and the count of available bikes changes every time a rider undocks or returns a bike. The pier-7 station has 12 docks and is one of the busiest.
Three parts of the system care about those changes. The rider app shows a live map screen with bike and free-dock counts. The operations team runs a rebalancing dispatcher that sends a van when a station has 2 or fewer bikes, or 2 or fewer free docks. The data team logs every change for demand forecasting.
The first version wired this directly. DockStation.undockBike() called mapScreen.refresh(), then dispatcher.check(), then logger.record(). Every new consumer meant editing DockStation. When marketing asked for a push notification to riders who favourited a station, the change touched the station class again, and its test suite had to construct fake map screens, fake vans and fake loggers just to test a counter.
The second problem showed up in production. Map screens are created every time a rider opens the app and destroyed when they leave. Someone added a list of screens to the station so it could refresh them, but nothing ever removed a screen from that list. After a day of traffic, a busy station held references to thousands of closed screens, each still being redrawn off-screen on every change, and the app's memory kept climbing until the operating system killed it.
The solution
What the pattern proposes.
Turn the station into a subject that knows only one thing about its consumers: they implement a small StationListener interface with a single method, onAvailabilityChanged(event). The station keeps a collection of listeners, exposes subscribe to add one, and calls every listener after each state change.
The station builds an immutable AvailabilityEvent containing the station id, bike count and free-dock count, and passes it to each listener. This is the push model: listeners get the data they need without reaching back into the station. The map screen redraws, the dispatcher compares the counts with its threshold, and the logger appends the event. Adding a push-notification feature becomes a new class plus one subscribe call. DockStation does not change.
To fix the leak, subscribe returns an unsubscribe function. Whoever subscribes owns that handle and must call it when the listener's lifetime ends, for example when a map screen closes. Making removal a value returned from registration puts the cleanup right next to the setup, where reviewers can see it.
Two details make the implementation robust. The station iterates over a snapshot of its listeners, so a listener that unsubscribes during a notification does not corrupt the loop. And it uses an insertion-ordered set, so subscribing the same object twice does not cause duplicate notifications.
An everyday analogy
The same idea, outside software.
Picture the coach of a youth football club on a rainy Saturday morning. She keeps a call list of parents. When the pitch is waterlogged and the match is cancelled, she goes down the list and rings everyone with the same message: match off, pitch closed. What each family does next is up to them. One goes back to bed, one books a swimming lesson, one tells grandparents not to drive over. The coach does not need to know any of that.
Parents join the list when their child signs up, and they are supposed to ask to be removed when the child leaves the club. If they forget, the coach keeps calling numbers that no longer care, and the list grows every season. That forgotten removal is exactly the listener leak you will be asked about in interviews.
Structure
The pieces and how they relate.
Participants
- Subject (DockStation)
- Owns the state that changes. Keeps a collection of listeners, offers subscribe and returns an unsubscribe handle, and notifies every listener after each state change. Depends only on the StationListener interface.
- Observer interface (StationListener)
- The single method every subscriber implements,
onAvailabilityChanged(event). It is the whole contract between the station and its consumers. - Event (AvailabilityEvent)
- An immutable snapshot of what changed: station id, bikes and free docks. Pushing it to listeners means they never need to query the station back mid-notification.
- Concrete observers (RiderMapScreen, RebalancingDispatcher, UsageLogger)
- Each reacts to the event in its own way: redraw, dispatch a van, or record. They can be added or removed without touching the station.
- Client (App bootstrap)
- Creates the station and the listeners, wires subscriptions, and holds the unsubscribe handles so it can release short-lived listeners such as screens.
Pseudocode
The solution to the scenario, language-neutral.
interface StationListener
method onAvailabilityChanged(event)
class DockStation
field id, capacity, bikes
field listeners = empty ordered set
method subscribe(listener)
listeners.add(listener)
return function unsubscribe()
listeners.remove(listener)
method undockBike()
if bikes == 0 then fail "station empty"
bikes = bikes - 1
notify()
method dockBike()
if bikes == capacity then fail "station full"
bikes = bikes + 1
notify()
private method notify()
event = AvailabilityEvent(id, bikes, capacity - bikes)
for each listener in copy(listeners)
listener.onAvailabilityChanged(event)
class RebalancingDispatcher implements StationListener
field threshold
method onAvailabilityChanged(event)
if event.bikes <= threshold then send van to deliver bikes
else if event.freeDocks <= threshold then send van to collect bikes
// wiring
station = DockStation("pier-7", capacity 12, bikes 3)
station.subscribe(RebalancingDispatcher(2))
station.subscribe(UsageLogger())
closeScreen = station.subscribe(RiderMapScreen("map-screen-1"))
station.undockBike() // all three react
closeScreen() // screen closed: release it
station.dockBike() // only dispatcher and logger reactThe code
The same solution in TypeScript, Python and PHP.
interface AvailabilityEvent {
readonly stationId: string;
readonly bikes: number;
readonly freeDocks: number;
}
interface StationListener {
onAvailabilityChanged(event: AvailabilityEvent): void;
}
class DockStation {
private readonly listeners = new Set<StationListener>();
private bikes: number;
constructor(readonly id: string, readonly capacity: number, bikes: number) {
this.bikes = bikes;
}
subscribe(listener: StationListener): () => void {
this.listeners.add(listener);
return () => {
this.listeners.delete(listener);
};
}
listenerCount(): number {
return this.listeners.size;
}
undockBike(): void {
if (this.bikes === 0) throw new Error(`${this.id} is empty`);
this.bikes--;
this.notify();
}
dockBike(): void {
if (this.bikes === this.capacity) throw new Error(`${this.id} is full`);
this.bikes++;
this.notify();
}
private notify(): void {
const event: AvailabilityEvent = {
stationId: this.id,
bikes: this.bikes,
freeDocks: this.capacity - this.bikes,
};
for (const listener of [...this.listeners]) {
listener.onAvailabilityChanged(event);
}
}
}
class RiderMapScreen implements StationListener {
constructor(private readonly name: string) {}
onAvailabilityChanged(e: AvailabilityEvent): void {
console.log(`[${this.name}] ${e.stationId}: ${e.bikes} bikes, ${e.freeDocks} free docks`);
}
}
class RebalancingDispatcher implements StationListener {
constructor(private readonly threshold: number) {}
onAvailabilityChanged(e: AvailabilityEvent): void {
if (e.bikes <= this.threshold) {
console.log(`Dispatch van: bring bikes to ${e.stationId}`);
} else if (e.freeDocks <= this.threshold) {
console.log(`Dispatch van: collect bikes from ${e.stationId}`);
}
}
}
class UsageLogger implements StationListener {
readonly events: AvailabilityEvent[] = [];
onAvailabilityChanged(e: AvailabilityEvent): void {
this.events.push(e);
}
}
const station = new DockStation("pier-7", 12, 3);
const logger = new UsageLogger();
station.subscribe(new RebalancingDispatcher(2));
station.subscribe(logger);
const closeScreen = station.subscribe(new RiderMapScreen("map-screen-1"));
station.undockBike();
// Dispatch van: bring bikes to pier-7
// [map-screen-1] pier-7: 2 bikes, 10 free docks
closeScreen(); // the rider left the screen: release it or it leaks
station.dockBike(); // 3 bikes, 9 free docks: only the logger records it
console.log(`listeners: ${station.listenerCount()}, logged events: ${logger.events.length}`);
// listeners: 2, logged events: 2from dataclasses import dataclass
from typing import Callable, Protocol
@dataclass(frozen=True)
class AvailabilityEvent:
station_id: str
bikes: int
free_docks: int
class StationListener(Protocol):
def on_availability_changed(self, event: AvailabilityEvent) -> None: ...
class DockStation:
def __init__(self, station_id: str, capacity: int, bikes: int) -> None:
self.id = station_id
self.capacity = capacity
self._bikes = bikes
# dict keys keep insertion order and ignore duplicates: an ordered set
self._listeners: dict[StationListener, None] = {}
def subscribe(self, listener: StationListener) -> Callable[[], None]:
self._listeners[listener] = None
def unsubscribe() -> None:
self._listeners.pop(listener, None)
return unsubscribe
def listener_count(self) -> int:
return len(self._listeners)
def undock_bike(self) -> None:
if self._bikes == 0:
raise RuntimeError(f"{self.id} is empty")
self._bikes -= 1
self._notify()
def dock_bike(self) -> None:
if self._bikes == self.capacity:
raise RuntimeError(f"{self.id} is full")
self._bikes += 1
self._notify()
def _notify(self) -> None:
event = AvailabilityEvent(self.id, self._bikes, self.capacity - self._bikes)
for listener in list(self._listeners):
listener.on_availability_changed(event)
class RiderMapScreen:
def __init__(self, name: str) -> None:
self._name = name
def on_availability_changed(self, e: AvailabilityEvent) -> None:
print(f"[{self._name}] {e.station_id}: {e.bikes} bikes, {e.free_docks} free docks")
class RebalancingDispatcher:
def __init__(self, threshold: int) -> None:
self._threshold = threshold
def on_availability_changed(self, e: AvailabilityEvent) -> None:
if e.bikes <= self._threshold:
print(f"Dispatch van: bring bikes to {e.station_id}")
elif e.free_docks <= self._threshold:
print(f"Dispatch van: collect bikes from {e.station_id}")
class UsageLogger:
def __init__(self) -> None:
self.events: list[AvailabilityEvent] = []
def on_availability_changed(self, e: AvailabilityEvent) -> None:
self.events.append(e)
if __name__ == "__main__":
station = DockStation("pier-7", 12, 3)
logger = UsageLogger()
station.subscribe(RebalancingDispatcher(2))
station.subscribe(logger)
close_screen = station.subscribe(RiderMapScreen("map-screen-1"))
station.undock_bike()
# Dispatch van: bring bikes to pier-7
# [map-screen-1] pier-7: 2 bikes, 10 free docks
close_screen() # the rider left the screen: release it or it leaks
station.dock_bike() # 3 bikes, 9 free docks: only the logger records it
print(f"listeners: {station.listener_count()}, logged events: {len(logger.events)}")
# listeners: 2, logged events: 2<?php
declare(strict_types=1);
final class AvailabilityEvent
{
public function __construct(
public readonly string $stationId,
public readonly int $bikes,
public readonly int $freeDocks,
) {
}
}
interface StationListener
{
public function onAvailabilityChanged(AvailabilityEvent $event): void;
}
final class DockStation
{
/** @var array<int, StationListener> keyed by object id: ordered, no duplicates */
private array $listeners = [];
public function __construct(
public readonly string $id,
public readonly int $capacity,
private int $bikes,
) {
}
public function subscribe(StationListener $listener): Closure
{
$key = spl_object_id($listener);
$this->listeners[$key] = $listener;
return function () use ($key): void {
unset($this->listeners[$key]);
};
}
public function listenerCount(): int
{
return count($this->listeners);
}
public function undockBike(): void
{
if ($this->bikes === 0) {
throw new RuntimeException("{$this->id} is empty");
}
$this->bikes--;
$this->notify();
}
public function dockBike(): void
{
if ($this->bikes === $this->capacity) {
throw new RuntimeException("{$this->id} is full");
}
$this->bikes++;
$this->notify();
}
private function notify(): void
{
$event = new AvailabilityEvent($this->id, $this->bikes, $this->capacity - $this->bikes);
// foreach over an array works on a copy, so unsubscribing mid-loop is safe
foreach ($this->listeners as $listener) {
$listener->onAvailabilityChanged($event);
}
}
}
final class RiderMapScreen implements StationListener
{
public function __construct(private readonly string $name)
{
}
public function onAvailabilityChanged(AvailabilityEvent $e): void
{
echo "[{$this->name}] {$e->stationId}: {$e->bikes} bikes, {$e->freeDocks} free docks\n";
}
}
final class RebalancingDispatcher implements StationListener
{
public function __construct(private readonly int $threshold)
{
}
public function onAvailabilityChanged(AvailabilityEvent $e): void
{
if ($e->bikes <= $this->threshold) {
echo "Dispatch van: bring bikes to {$e->stationId}\n";
} elseif ($e->freeDocks <= $this->threshold) {
echo "Dispatch van: collect bikes from {$e->stationId}\n";
}
}
}
final class UsageLogger implements StationListener
{
/** @var list<AvailabilityEvent> */
public array $events = [];
public function onAvailabilityChanged(AvailabilityEvent $e): void
{
$this->events[] = $e;
}
}
$station = new DockStation('pier-7', 12, 3);
$logger = new UsageLogger();
$station->subscribe(new RebalancingDispatcher(2));
$station->subscribe($logger);
$closeScreen = $station->subscribe(new RiderMapScreen('map-screen-1'));
$station->undockBike();
// Dispatch van: bring bikes to pier-7
// [map-screen-1] pier-7: 2 bikes, 10 free docks
$closeScreen(); // the rider left the screen: release it or it leaks
$station->dockBike(); // 3 bikes, 9 free docks: only the logger records it
echo 'listeners: ' . $station->listenerCount() . ', logged events: ' . count($logger->events) . "\n";
// listeners: 2, logged events: 2When to use it
Situations where it pays off.
Several parts of the system must react when one object changes, and the set of reacting parts grows or varies over time.
The subject loops over an interface instead of calling named collaborators, so new reactions are new classes rather than edits to the subject. That keeps the subject stable and testable on its own.
Consumers come and go at runtime, such as UI screens, websocket connections or temporary monitors.
Subscribe and unsubscribe are runtime operations. A list of hard-coded calls cannot express a screen that exists for 40 seconds and then disappears.
A lower-level module must inform a higher-level one without importing it.
The station lives in the domain layer and has no idea that a mobile map or a van-dispatch service exists. Observer inverts the dependency: the outer layers depend on the station's listener interface, not the other way round.
You want to cut a growing method that ends in a string of side-effect calls to unrelated components.
Replacing those calls with one notify step separates the core state change from its consequences, which is easier to read, review and test.
How to implement it
Steps to introduce it in existing code.
Identify the subject: the object whose state changes and the exact moments that count as a change. For the station, that is after
dockBikeandundockBikesucceed.Define a small observer interface with one method per kind of event. Keep it narrow; a listener should not have to implement methods it ignores.
Decide on push or pull. Pushing an immutable event object is usually safer than handing out the subject, because listeners cannot mutate it or read half-updated state.
Give the subject a collection of listeners plus a
subscribemethod that returns an unsubscribe handle. Use an ordered set so double subscription is harmless and order is predictable.Notify after the state is fully updated, iterating over a copy of the collection so listeners can unsubscribe themselves during delivery.
Move each former direct call into its own observer class and register it during application wiring.
For every short-lived subscriber, store the unsubscribe handle in the object that owns its lifetime and call it in the teardown path: screen close, component unmount, connection drop.
Decide and document failure behaviour: whether one listener's exception stops the others, and whether delivery is synchronous or queued.
Pros and cons
What you gain and what you pay.
Pros
- Open/Closed in practice: new reactions to a station change are new classes, and
DockStationstays untouched. - The subject depends only on a tiny interface, so it can be unit tested with a single recording listener.
- Subscriptions are dynamic, which fits UI screens and connections that appear and disappear at runtime.
- Each observer has one job, which keeps the redraw, dispatch and logging logic in separate, focused classes.
Cons
- Forgotten unsubscriptions leak memory: the subject's collection keeps every registered listener reachable, along with everything that listener references.
- Control flow becomes implicit. Reading
undockBikeno longer tells you what happens next, so debugging means finding every subscriber. - Synchronous notification means one slow or throwing listener delays or breaks the rest and the caller.
- Cascades are easy to create by accident: a listener that changes another subject can trigger long or even circular notification chains.
- Depending on notification order between listeners is fragile, yet tempting once there are many of them.
Relations with other guides
Patterns it's often confused or combined with.
- Mediator: Route Component Chatter Through One Coordinator
Mediator centralises the interaction logic between colleagues in one object. Observer spreads reactions across independent subscribers. A mediator is often implemented using Observer underneath, with colleagues subscribing to it.
- Command Pattern: Turn Requests into Objects You Can Queue and Undo
Commands can be the payload an observer receives, or a listener can wrap a command to run later. Both decouple the sender of a request from the code that executes it.
- Transactional Outbox: Commit State and Events Together
When observers live in other services, in-memory notification is lost on a crash. An outbox stores the event in the same database transaction as the state change, then publishes it reliably.
- Change Data Capture: Stream Database Changes from the Log
Change data capture is Observer at the database level: consumers subscribe to the change log instead of the application calling them, so even writes from other code paths are seen.
- Shotgun Surgery: When One Change Means Edits in Many Files
If adding one reaction to a state change means editing the subject and several callers, Observer collapses that into one new subscriber class.
- Backpressure: Let Slow Consumers Slow Down Fast Producers
Once notification becomes asynchronous, a fast subject can flood slow listeners. Backpressure is how you keep queued events from growing without bound.
Common questions
Short answers to the usual doubts.
Why does Observer cause memory leaks, and how do you prevent them?
The subject's listener collection holds a strong reference to every subscriber. As long as the subject is reachable, so is each listener and everything it references, such as a whole screen and its views. In the example, a long-lived pier-7 station would keep every closed map screen alive. Prevent it by returning an unsubscribe handle from subscribe and calling it in the owner's teardown path, or by tying subscriptions to a lifecycle object that releases them all at once, such as an AbortSignal in the browser or a disposable bag in a component.
Should I use weak references for listeners instead?
Sometimes, but not as the default. Weak references (WeakRef in JavaScript, weakref.WeakMethod in Python, WeakReference in PHP) stop the subject from keeping listeners alive, but they also mean a listener may silently vanish once nothing else holds it, and when that happens depends on the garbage collector. Anonymous callbacks are especially prone to disappearing immediately. Explicit unsubscription is predictable and testable. Use weak references only when ownership truly cannot be expressed, and document it.
What happens if one listener throws during notification?
In the plain synchronous loop shown here, the exception propagates out of notify, the remaining listeners are skipped, and the caller of undockBike sees the error even though the bike count already changed. If listeners are independent, catch per listener, report the error, and continue. Whatever you choose, decide it deliberately; interviewers often ask exactly this.
How is Observer different from publish-subscribe?
In classic Observer the subscriber registers directly with the subject and is called in-process, usually synchronously. Publish-subscribe puts a broker or event bus between them: publishers emit to a topic, subscribers listen to the topic, and neither knows the other exists. Pub-sub adds decoupling, and often asynchronous or cross-process delivery, at the cost of another moving part and weaker guarantees about ordering and delivery.
Can listeners rely on being notified in a particular order?
They should not. The examples use insertion-ordered collections, so order is deterministic, which helps tests and debugging. But if the dispatcher only works correctly after the logger has run, you have a hidden dependency between observers. Either merge them, or have one explicitly trigger the other.
Push or pull: should the event carry the data or should listeners query the subject?
Push an immutable event when listeners need a known, small set of facts, as with bikes and free docks here. It avoids listeners reading the subject in a half-updated state and keeps them from calling mutating methods mid-notification. Pull, passing the subject itself, suits cases where listeners need very different data and building a full event each time would be wasteful.