creational

Observer

Define a one-to-many dependency so dependents are notified automatically when state changes.

When one object's state needs to be reflected in several others — a spreadsheet cell feeding three charts, a data model backing multiple views — the naive approach has the source call each dependent directly. That hard-wires the source to know every consumer, so adding a new consumer means editing the source, and the source ends up coupled to things that are really none of its business. Observer inverts this: dependents subscribe to the source, and the source broadcasts changes without knowing who is listening.

A YouTube channel — upload a video and all subscribers get notified. Subscribers can join or leave freely.

Key Concepts

1
The subject (publisher) keeps a list of observers (subscribers) and offers methods to subscribe and unsubscribe. When its state changes it walks the list and calls a notification method on each observer, handing over the relevant data. Observers implement a shared listener interface, so the subject holds them only by that abstract type and stays ignorant of their concrete classes. New observers can come and go at runtime without the subject changing at all, which is what makes event-driven and reactive systems composable.
2
It underpins UI event handling, the model-view separation in MVC, pub/sub messaging, and live data feeds like stock tickers and sensor streams. Three hazards are worth naming in an interview: observers that forget to unsubscribe cause memory leaks, because the subject's reference keeps them alive (the lapsed-listener problem); a notification that triggers further state changes can cascade into unexpected chains or even infinite loops; and the order in which observers are notified is generally undefined, so observers must not depend on running before or after one another.