Stock Market Notification System - Observer Pattern Implementation
This is an implementation of the Observer design pattern for a trading application where investors receive real-time stock price updates through different notification channels.
Problem Statement
Building a backend for a trading app like Zerodha or Robinhood where multiple investors need to be notified when stock prices change. Unlike simple notifications, stock updates need to convey both the stock name and the current price. Different investors may prefer different notification channels (email, mobile app, SMS, etc.).
Key Challenge: The system must support personalized notifications for multiple users across different communication channels, while maintaining loose coupling between the stock ticker and the notification mechanisms.
Class Diagram
+------------------+ +-----------------------+
| Subject | | Observer |
| (Interface) | | (Interface) |
+------------------+ +-----------------------+
| + add(obs) | | + update(name, price) |
| + remove(obs) | +-----------+-----------+
| + notify() | ^
+--------+---------+ |
^ | (Implements)
| (Implements) |
| |
+--------+---------+ +-----------+-----------+----------------+
| StockTicker |<>---------->| | |
+------------------+ (List) | +----------------+ | +----------+ |
| - observers List | | | EmailObserver | | |AppObserver| |
| - stockName | | +----------------+ | +----------+ |
| - stockPrice | | | - username | | | -username| |
| + setStockPrice()| | | + update() | | | +update()| |
+------------------+ | +----------------+ | +----------+ |
+-----------------------+----------------+
Implementation
package observer.stockmarketnotificationsystem;
import java.util.ArrayList;
import java.util.List;
/**
* Main class for the Stock Market Notification System.
* Demonstrates the Observer Pattern with distinct User Identities.
*/
public class StockMarketNotificationSystem {
/**
* Observer Interface.
* Represents the "Investor" who wants to be notified.
*/
interface Observer {
void update(String stockName, double stockPrice);
}
/**
* Subject Interface.
* Represents the "Stock Market" or "Ticker" that broadcasts updates.
*/
interface Subject {
void addObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
/**
* Concrete Subject.
* This acts as the central ticker. When a stock updates, it alerts everyone.
*/
static class StockTicker implements Subject {
// List to hold all subscribed investors
private final List<Observer> observers = new ArrayList<>();
private String stockName;
private double stockPrice;
@Override
public void addObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
// Pass the state to the observers
observer.update(stockName, stockPrice);
}
}
public void setStockPrice(String stockName, double stockPrice) {
this.stockName = stockName;
this.stockPrice = stockPrice;
System.out.println("\n[Ticker] New Update: " + stockName +
" is now $" + stockPrice);
notifyObservers();
}
}
/**
* Concrete Observer for Email Alerts.
* Contains the User's Name to make it personalized.
*/
static class EmailObserver implements Observer {
private final String username;
public EmailObserver(String username) {
this.username = username;
}
@Override
public void update(String stockName, double stockPrice) {
System.out.println(" -> Email sent to " + username + ": " +
stockName + " is at $" + stockPrice);
}
}
/**
* Concrete Observer for Mobile App Alerts.
*/
static class AppObserver implements Observer {
private final String username;
public AppObserver(String username) {
this.username = username;
}
@Override
public void update(String stockName, double stockPrice) {
System.out.println(" -> App Notification for " + username + ": " +
stockName + " is at $" + stockPrice);
}
}
/**
* Main Driver Method.
*/
public static void main(String[] args) {
StockTicker zerodha = new StockTicker();
System.out.println("\n--- Simulation Started ---");
// 1. Create Observers with Names (Identity)
Observer shiv = new AppObserver("Shiv");
Observer tina = new AppObserver("Tina");
Observer laxmi = new EmailObserver("Laxmi");
// 2. Subscribe them
zerodha.addObserver(shiv);
zerodha.addObserver(tina);
zerodha.addObserver(laxmi);
// 3. Update Price - Everyone gets notified
zerodha.setStockPrice("Apple", 238.92);
// 4. Unsubscribe Logic
System.out.println("\n--- Shiv unsubscribes ---");
zerodha.removeObserver(shiv);
// 5. Update Price again - Shiv should NOT receive this
zerodha.setStockPrice("Tesla", 500.00);
}
}
Key Features
- Observer Pattern: Implements one-to-many dependency for stock price updates
- Personalized Notifications: Each observer has a username for personalized messages
- Multiple Notification Channels: Supports email, mobile app, and easily extensible to SMS, desktop, etc.
- Multi-parameter Updates: Unlike simple observer patterns, this passes both stock name and price
- Dynamic Subscription: Investors can subscribe and unsubscribe at runtime
- Loose Coupling: StockTicker doesn't need to know about specific notification implementations
How It Works
- Subject (StockTicker): Maintains stock state and list of observers
-
Observers (EmailObserver, AppObserver): Implement the
Observerinterface with personalized identities -
Registration: Investors register using
addObserver() -
Notification: When stock price changes via
setStockPrice(), all registered observers receive updates with both stock name and price -
Unsubscription: Investors can unsubscribe using
removeObserver()
Sample Output
--- Simulation Started ---
[Ticker] New Update: Apple is now $238.92
-> App Notification for Shiv: Apple is at $238.92
-> App Notification for Tina: Apple is at $238.92
-> Email sent to Laxmi: Apple is at $238.92
--- Shiv unsubscribes ---
[Ticker] New Update: Tesla is now $500.0
-> App Notification for Tina: Tesla is at $500.0
-> Email sent to Laxmi: Tesla is at $500.0
Real-World Applications
- Stock trading platforms (Zerodha, Robinhood, E*TRADE)
- Cryptocurrency price tracking
- Real-time sports score updates
- News notification systems
- Social media feed updates
Top comments (0)