Loading...
Learn Observer Pattern — a key concept for LLD interviews.
Observer Pattern: when one object changes state, all dependents are notified automatically. Like YouTube — upload a video, all subscribers get notified. Decouples the publisher from subscribers.
You're building a stock trading platform. When a stock price changes, the dashboard chart needs to update, price alerts need to fire, a trade log must be written, and the portfolio value needs recalculating. Right now, the StockPrice class directly calls all these systems. Adding a new feature (like a mobile push notification) means modifying StockPrice every time.
class StockPrice {
private price: number
private dashboard: DashboardChart
private alertSystem: PriceAlertSystem
private tradeLog: TradeLogger
private portfolio: PortfolioCalculator
updatePrice(newPrice: number) {
this.price = newPrice
// Directly calling every dependent system
this.dashboard.refreshChart(this.symbol, newPrice)
this.alertSystem.checkAlerts(this.symbol, newPrice)
this.tradeLog.logPriceChange(this.symbol, newPrice)
this.portfolio.recalculate(this.symbol, newPrice)
// TODO: mobile notifications, analytics, audit...
}
}What's the fundamental design problem here?