design patterns ·

Observer

Defines a one-to-many dependency so when one object changes state, all its dependents are notified automatically.

easy0.5hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

When multiple objects need to react to changes in one object, hardcoding their relationships creates tight coupling. Observer lets the subject maintain a list of observers and notify them automatically on state change.

Subject maintains a list of Observers. subscribe() adds, unsubscribe() removes. When state changes, the subject calls update() on all registered observers. Observers react independently.

When to use

Event systems, GUI event listeners, MVC (model notifies views), real-time data feeds (stock prices, weather), reactive programming foundations.

When not to

When notification order matters and must be guaranteed. When observers are always the same set - direct method calls are clearer.

Key insights

  • Java's java.util.Observable and EventListener are built-in Observer implementations
  • Weak references for observers prevent memory leaks when observers are garbage-collected
  • The push model (subject sends data in update()) vs pull model (observer queries subject) are two variants
  • RxJava, ReactiveX, and Node.js EventEmitter all implement Observer