behavioral

Observer

Define a subscription mechanism so multiple observers can react to subject events without the subject knowing concrete subscriber details.

Problem

behavioral

A system needs to notify multiple dependent objects when state changes occur, but hardcoding those dependencies makes the design rigid and tightly coupled.

Integration notes

Observers work well inside a single application boundary for UI events, domain events, and in-process notifications where subscribers change dynamically.

Tradeoffs

  • Notification flows can become hard to trace when many observers react to the same event
  • Observers may receive updates they do not need unless subscriptions are carefully designed

Languages

typescript, java, python, angular, react, react-native, csharp, dotnet

Platforms

Web, Backend, Event-driven systems

Variants

Scenarios

Stock price alerts

A stock subject notifies dashboards and alert services whenever the tracked price changes.

Language examples

Core languages

Frameworks and libraries

Stock price alertstypescript

The stock acts as the subject, while displays and alerts subscribe independently and react when the price changes.

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

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

  constructor(private price: number) {}

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

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

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

  private notify(): void {
    this.observers.forEach((observer) => observer.update(this.price));
  }
}

class PriceDisplay implements Observer {
  update(price: number): void {
    console.log(`Display updated: ${price}`);
  }
}

class PriceAlert implements Observer {
  update(price: number): void {
    if (price > 100) {
      console.log(`Alert: stock price is ${price}`);
    }
  }
}

const stock = new Stock(95);
stock.subscribe(new PriceDisplay());
stock.subscribe(new PriceAlert());
stock.setPrice(105);

Real-world examples

  • UI event listeners: Buttons, forms, and state containers notify multiple listeners when user interactions or state changes occur.
  • Order and domain events: Order status changes can trigger email, analytics, inventory, and fulfillment reactions without hardcoded dependencies.
  • Content subscriptions: Newsletters, mobile apps, and web feeds can all subscribe to publication events from a shared content source.