3.7 Observer
The Observer pattern defines a one-to-many dependency between objects: when one object (the Subject) changes state, all objects that depend on it (Observers) are notified automatically and update. It is the most classic object-oriented expression of publish-subscribe.
The lab below lets you toggle the subscription state of several displays, then click "notify" and see that only subscribers receive the push.
The subject doesn't know its concrete observers
interface Observer { void update(float temp); }
class WeatherStation { // Subject
private List<Observer> observers = new ArrayList<>();
public void subscribe(Observer o) { observers.add(o); }
public void unsubscribe(Observer o) { observers.remove(o); }
public void setTemp(float t) {
this.temp = t;
for (Observer o : observers) o.update(t); // notify each
}
}Key point: the subject holds only a list of the Observer interface and neither knows nor cares whether a phone, web page, or TV is listening. This lets you add and remove observers freely without changing a line of the subject. In the weather-station lab below, drag the temperature and every online display updates instantly.
Push vs pull, and the pitfalls
- Push model: the subject pushes data straight to observers (
update(temp)). Simple, but observers may receive data they don't need.
- Pull model: the subject only signals "I changed," and observers pull what they need (
update(subject)). More flexible, slightly more coupled.
Common pitfalls:
- Notification storms: one change triggers a flood of cascading updates, hurting performance.
- Update order: if observers have implicit dependencies, ordering is hard to guarantee.
- Memory leaks: forgetting to
unsubscribekeeps the subject holding observer references so objects can't be reclaimed (common with Java listeners and frontend events).
Real-world echoes
From GUI events and EventEmitter to RxJS/reactive programming, message buses, and views listening to models in MVC — Observer is everywhere. Understanding its "notification storms" and "unsubscribe leaks" helps you write more robust reactive code.