Deep Dive
low level designdesign patternsoop

Observer Pattern: Broadcast State Without Knowing Who's Listening

When one object changes and an unknown, shifting crowd must react, wiring the subject to each dependent is a maintenance trap. Observer inverts it — dependents subscribe, the subject just broadcasts.

·15 min read
Medium

A WeatherStation object gets a new reading every few seconds. The dashboard widget needs to repaint. The forecast cache needs to invalidate. Analytics wants an event. Logging wants a line. So setReading() grows a body: update the widget, poke the cache, fire the analytics call, write the log.

Then the mobile team wants push notifications on it. Then someone adds an SMS alert for storms. Each new consumer is another line inside the one method that owns the reading — and now that method imports the UI layer, the cache layer, the analytics client, and the notification service. The thing whose only job is “I have a new number” has become the hub every dependent is soldered to. Delete a consumer and you edit the station. Reorder them and you might break one. The station knows far too much about a crowd that keeps changing.

The problem isn’t the number of consumers. It’s the direction of the dependency: the source of truth points at everyone who cares about it, so it can’t change — or be tested — without dragging all of them along.

The intuition: a newsletter doesn’t know its readers

Think about a newsletter. The publisher writes one issue and hits send. They do not keep a mental list of who you are, whether you’ll read it, or what you’ll do with it. They keep a subscription list — and readers put themselves on it and take themselves off it. When a new issue ships, everyone currently subscribed gets it, in one broadcast.

That inversion is the whole pattern. The publisher (the subject) owns the state and the list. The readers (the observers) own the reacting. Crucially, subscription is the reader’s decision, not the publisher’s — which is exactly why the publisher can stay ignorant of who’s out there.

The members-only walkthrough picks up from here: the two-interface structure and class diagram, push vs pull, the full code for the contracts, the subject, and three unrelated observers, the real-world sightings (DOM, Redux, Spring, RxJava), the tradeoffs, and an interview corner with a coding challenge and quiz.

Members only

Keep reading with Premium

You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.

Related Articles