Observer pattern in Java
A classic real-life example of the Event Listener (or Observer) pattern in Java is a Stock Market Notifier.
The Producer is the Stock Exchange (the stock price), and the Subscribers are the individual investors who want to be notified when the price changes.
Real-Life Example: Stock Price Notifier 📈
Imagine a system where traders need immediate alerts when a specific stock hits a target price.
- Producer (The Subject): The
StockExchangeclass. It holds the current price and a list of all traders watching that price. - Subscriber (The Observer): The
Traderinterface/class. It implements the method that gets called when the price changes.
Java Code Implementation
1. The Listener Interface (The Contract)
First, we define the interface that all Subscribers must implement.
// 1. The Listener Interface (The contract for all Observers)
public interface PriceChangeListener {
void priceChanged(String stockSymbol, double newPrice);
}
2. The Subscriber (The Trader)
A Trader implements the listener interface and defines their reaction to the event.
// 2. The Concrete Subscriber (The Observer/Listener)
public class Trader implements PriceChangeListener {
private String name;
private double targetPrice;
public Trader(String name, double targetPrice) {
this.name = name;
this.targetPrice = targetPrice;
}
// This method is invoked by the Producer when the event occurs
@Override
public void priceChanged(String stockSymbol, double newPrice) {
System.out.println(name + " received alert: " + stockSymbol + " is now $" + newPrice);
if (newPrice >= targetPrice) {
System.out.println(" >> " + name + " ALERT: Price hit your target of $" + targetPrice + "!");
}
}
}
3. The Producer (The Subject)
The StockExchange holds the list of subscribers and manages the notification logic.
import java.util.ArrayList;
import java.util.List;
// 3. The Producer (The Subject/Observable)
public class StockExchange {
// Holds the list of registered Subscribers
private List<PriceChangeListener> subscribers = new ArrayList<>();
private double currentPrice;
private String symbol;
public StockExchange(String symbol, double initialPrice) {
this.symbol = symbol;
this.currentPrice = initialPrice;
}
// Method for Subscribers to register
public void addListener(PriceChangeListener listener) {
subscribers.add(listener);
System.out.println("-> New listener registered.");
}
// The core event-generation method
public void updatePrice(double newPrice) {
if (newPrice != currentPrice) {
this.currentPrice = newPrice;
System.out.println("\n*** EVENT: Price of " + symbol + " changed to $" + newPrice + " ***");
// Invoke methods of ALL registered Subscribers (The Notification)
notifyListeners();
}
}
// Iterates through the subscribers and calls the notification method
private void notifyListeners() {
for (PriceChangeListener listener : subscribers) {
listener.priceChanged(symbol, currentPrice);
}
}
}
4. Running the Example
public class ObserverDemo {
public static void main(String[] args) {
StockExchange aaplStock = new StockExchange("AAPL", 150.00);
// 1. Multiple Subscribers register with the Producer
Trader investorA = new Trader("Investor Alice", 155.00);
Trader investorB = new Trader("Investor Bob", 160.00);
aaplStock.addListener(investorA);
aaplStock.addListener(investorB);
// 2. Event 1: Price changes, but is below targets
aaplStock.updatePrice(152.50);
// 3. Event 2: Price changes, hitting Alice's target
aaplStock.updatePrice(155.00);
// 4. Event 3: Price changes, hitting Bob's target
aaplStock.updatePrice(161.00);
}
}
Output
-> New listener registered.
-> New listener registered.
*** EVENT: Price of AAPL changed to $152.5 ***
Investor Alice received alert: AAPL is now $152.5
Investor Bob received alert: AAPL is now $152.5
*** EVENT: Price of AAPL changed to $155.0 ***
Investor Alice received alert: AAPL is now $155.0
>> Investor Alice ALERT: Price hit your target of $155.0!
Investor Bob received alert: AAPL is now $155.0
*** EVENT: Price of AAPL changed to $161.0 ***
Investor Alice received alert: AAPL is now $161.0
>> Investor Alice ALERT: Price hit your target of $155.0!
Investor Bob received alert: AAPL is now $161.0
>> Investor Bob ALERT: Price hit your target of $160.0!
Published on: Oct 05, 2025, 10:58 AM