100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Software Design

Observer Pattern

The Observer pattern lets a Subject notify a dynamic list of Observers automatically whenever its state changes, decoupling event producers from consumers.

Behavioral Patterns IIntermediate9 min readJul 10, 2026
Analogies

What Is the Observer Pattern?

The Observer pattern defines a one-to-many dependency where a Subject maintains a list of Observer objects and notifies them automatically whenever its state changes, without needing to know any concrete details about those observers beyond a common interface. This decouples the object that owns the data from the objects that react to changes in it, which is the foundation of event-driven UI frameworks, pub/sub messaging systems, and reactive programming libraries.

🏏

Cricket analogy: A stadium's giant scoreboard (Subject) broadcasts every run and wicket to thousands of fans (Observers) simultaneously, and the scoreboard doesn't need to know who's watching or why, just that a change occurred.

Structure: Subject and Observers

Concretely, the Subject exposes subscribe()/unsubscribe() (or attach()/detach()) methods that add or remove Observer references from an internal list, plus a notify() method that iterates that list and calls each observer's update() method. Observers implement a common interface, typically a single update(data) method, so the Subject can treat every observer polymorphically regardless of what concrete class it belongs to, keeping the coupling limited to that one interface.

🏏

Cricket analogy: A cricket app's 'follow match' button is the subscribe() call adding your device to the Subject's observer list, and every ball bowled triggers notify() which calls update() on every follower's push-notification handler.

typescript
interface Observer {
  update(data: { price: number }): void;
}

class StockTicker {
  private observers: Observer[] = [];

  subscribe(observer: Observer): void {
    this.observers.push(observer);
  }

  unsubscribe(observer: Observer): void {
    this.observers = this.observers.filter(o => o !== observer);
  }

  private notify(price: number): void {
    for (const observer of this.observers) {
      observer.update({ price });
    }
  }

  setPrice(price: number): void {
    this.notify(price);
  }
}

class PriceAlert implements Observer {
  constructor(private threshold: number) {}
  update({ price }: { price: number }): void {
    if (price > this.threshold) {
      console.log(`Alert: price ${price} crossed ${this.threshold}`);
    }
  }
}

const ticker = new StockTicker();
const alert = new PriceAlert(100);
ticker.subscribe(alert);
ticker.setPrice(105);

Push vs Pull Models

In the push model, the Subject sends the full changed data as an argument to update(data), which is simple but can waste bandwidth if observers only care about part of the change; in the pull model, the Subject just calls update() with a reference to itself, and each observer queries the Subject's getters for exactly the state it needs, which is more flexible but couples observers to the Subject's public interface more tightly. Most production event systems (DOM events, RxJS) use a hybrid: a lightweight event payload plus the ability to look up more context if needed.

🏏

Cricket analogy: A push-model TV broadcast shoves the full replay footage to every viewer whether they want it or not, while a pull-model text-commentary app lets each fan query just the scorecard detail they care about, like strike rate.

RxJS Observables and the DOM's addEventListener are both large-scale, production-hardened Observer implementations. Studying their APIs — subscribe/unsubscribe, event objects with lazy getters — is a fast way to see the pattern's push/pull hybrid in real code.

Common Pitfalls

The most common Observer bug is forgetting to unsubscribe, which leaks memory because the Subject's reference list keeps dead or discarded observers alive indefinitely — this is especially dangerous in long-lived UI components where a screen is dismissed but its listener is never detached. A second pitfall is notification storms: if an observer's update() method itself triggers a change on the Subject, you can get infinite or exponentially cascading notify() calls unless the implementation guards against re-entrant updates.

🏏

Cricket analogy: Forgetting to unsubscribe from a match's push notifications means your phone keeps buzzing for that stadium's future unrelated events months later, exactly like a dangling observer reference that never gets detached.

Always pair subscribe() with a corresponding unsubscribe() in the same lifecycle scope (e.g., component mount/unmount). An Observer implementation without a reliable detach path is a memory leak waiting to happen, especially in single-page applications with frequently created and destroyed components.

  • Observer establishes a one-to-many dependency: a Subject notifies all subscribed Observers automatically when its state changes.
  • Subjects expose subscribe()/unsubscribe() and notify(); Observers implement a shared update() method.
  • The pattern decouples event producers from consumers, powering event-driven UIs and pub/sub systems.
  • The push model sends full data with each notification; the pull model has observers query the Subject for what they need.
  • Forgetting to unsubscribe is the most common bug, causing memory leaks from observers that outlive their relevance.
  • Re-entrant updates (an observer changing the Subject inside update()) can cause notification storms without guards.
  • Production frameworks like RxJS and the DOM event system are real-world, hybrid push/pull Observer implementations.

Practice what you learned

Was this page helpful?

Topics covered

#SoftwareDesign#DesignPatternsStudyNotes#SoftwareEngineering#ObserverPattern#Observer#Pattern#Structure#Subject#StudyNotes#SkillVeris