Design PatternsL3 · Medium
Observer Pattern: Stock Price Alerts
Problem
Design a StockMarket system where multiple observers (mobile app, email alert, dashboard widget) are notified whenever a stock price changes. Observers can subscribe and unsubscribe at runtime without the StockMarket knowing what they are.
Requirements
- StockObserver interface with: onPriceChange(symbol, oldPrice, newPrice)
- StockMarket (subject) with: subscribe(observer), unsubscribe(observer), updatePrice(symbol, price)
- MobileAlertObserver, EmailAlertObserver, DashboardObserver each implement StockObserver
- When price changes, all subscribed observers are notified automatically
- Show: add observer, trigger price update, remove observer, trigger again — removed observer should NOT fire
Constraints
- –StockMarket must not import or reference any concrete Observer class
- –Notifications happen synchronously in order of subscription
✓ Saved