Observer in Stock Market App

This program integrates Observer pattern in stock market app.

Problem Statement

Write a Java program where Stock notifies multiple investors when price changes.

Source Code

1 import java.util.*;
2 interface Investor { void update(double price); }
3 class Stock {
4 List<Investor> investors=new ArrayList<>();
5 double price;
6 void addInvestor(Investor i){ investors.add(i); }
7 void setPrice(double p){ price=p; notifyInvestors(); }
8 void notifyInvestors(){ for(Investor i:investors) i.update(price); }
9 }
10 class ConcreteInvestor implements Investor {
11 String name;
12 ConcreteInvestor(String n){ name=n; }
13 public void update(double price){ System.out.println(name+" notified: Price = "+price); }
14 }
15 public class StockMarketApp {
16 public static void main(String[] args) {
17 System.out.println("Eduinq Stock Market App");
18 Stock s=new Stock();
19 s.addInvestor(new ConcreteInvestor("Investor1"));
20 s.addInvestor(new ConcreteInvestor("Investor2"));
21 s.setPrice(120.5);
22 }
23 }

Program Output

Eduinq Stock Market App
Investor1 notified: Price = 120.5
Investor2 notified: Price = 120.5

Explanation

Stock acts as Subject, Investors as Observers. - Price change triggers notifications. - This models real world enterprise apps like trading platforms. Conclusion: Shows Observer integration in enterprise apps.

Quick Links to Explore