Observer
Notify many dependent objects automatically when one object changes.
Use it when
Changes to one object must be reflected in others without tight coupling.
/**
* Observer: a stock tells everyone who subscribed when its price changes.
*
* Real-world scenario: a trading app. A price display and a price alert both care
* about a stock's price. Instead of each of them checking the price over and
* over, they subscribe once. Whenever the price changes, the stock notifies every
* subscriber. The stock doesn't know what they do with the news, and observers
* can subscribe or unsubscribe at any time.
*/
// Observer: anything that wants price updates.
interface PriceObserver {
update(stock: Stock): void;
}
// Subject: holds the state and notifies observers when it changes.
class Stock {
readonly symbol: string;
private currentPrice: number;
private readonly observers = new Set<PriceObserver>(); // no duplicates; keeps order
constructor(symbol: string, price: number) {
this.symbol = symbol;
this.currentPrice = price;
}
subscribe(observer: PriceObserver): void {
this.observers.add(observer);
}
unsubscribe(observer: PriceObserver): void {
this.observers.delete(observer);
}
get price(): number {
return this.currentPrice;
}
setPrice(price: number): void {
this.currentPrice = price;
for (const observer of this.observers) {
observer.update(this); // observers read what they need from the stock
}
}
}
// Concrete observers: each reacts in its own way.
class PriceDisplay implements PriceObserver {
update(stock: Stock): void {
console.log(` Display: ${stock.symbol} is now $${stock.price.toFixed(2)}`);
}
}
class BuyAlert implements PriceObserver {
private readonly target: number;
constructor(target: number) {
this.target = target;
}
update(stock: Stock): void {
if (stock.price <= this.target) {
console.log(` Alert: ${stock.symbol} at $${stock.price.toFixed(2)}, time to buy!`);
}
}
}
function clientCode(): void {
const stock = new Stock("ACME", 120);
const display = new PriceDisplay();
const alert = new BuyAlert(100);
stock.subscribe(display);
stock.subscribe(alert);
console.log("Price changes to 110:");
stock.setPrice(110);
console.log("Price changes to 95:");
stock.setPrice(95);
stock.unsubscribe(display);
console.log("Price changes to 90 (display unsubscribed):");
stock.setPrice(90);
}
clientCode();
// Output:
// Price changes to 110:
// Display: ACME is now $110.00
// Price changes to 95:
// Display: ACME is now $95.00
// Alert: ACME at $95.00, time to buy!
// Price changes to 90 (display unsubscribed):
// Alert: ACME at $90.00, time to buy!How it works
| Role | Classes | What it does |
|---|---|---|
| Subject | Stock | Holds the price and notifies every subscriber (kept in a Set) when it changes |
| Observer | PriceObserver | Interface with update(stock) |
| Concrete observers | PriceDisplay, BuyAlert | Each reacts in its own way: show the price, or alert below a target |
| Client | clientCode() | Subscribes observers, changes the price and unsubscribes one |