-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassignment8pt1.java
97 lines (78 loc) · 2.36 KB
/
assignment8pt1.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.ArrayList;
import java.util.List;
interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
class Stock implements Subject {
private String symbol;
private double price;
private List<Observer> investors;
public Stock(String symbol, double price) {
this.symbol = symbol;
this.price = price;
this.investors = new ArrayList<>();
}
public void setPrice(double price) {
this.price = price;
notifyObservers();
}
@Override
public void registerObserver(Observer observer) {
if (!investors.contains(observer)) {
investors.add(observer);
}
}
@Override
public void removeObserver(Observer observer) {
investors.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer investor : investors) {
investor.update(symbol, price);
}
}
}
interface Observer {
void update(String symbol, double price);
}
class Investor implements Observer {
private String name;
private List<Stock> stocks;
public Investor(String name) {
this.name = name;
this.stocks = new ArrayList<>();
}
public void investIn(Stock stock) {
if (!stocks.contains(stock)) {
stocks.add(stock);
stock.registerObserver(this);
}
}
public void divestFrom(Stock stock) {
if (stocks.contains(stock)) {
stocks.remove(stock);
stock.removeObserver(this);
}
}
@Override
public void update(String symbol, double price) {
System.out.println("Hello " + name + "! " + symbol + " price is now " + price);
}
}
public class assignment8pt1 {
public static void main(String[] args) {
Stock appleStock = new Stock("AAPL", 150.0);
Stock googleStock = new Stock("GOOGL", 2500.0);
Investor investor1 = new Investor("Alice");
Investor investor2 = new Investor("Bob");
investor1.investIn(appleStock);
investor2.investIn(googleStock);
appleStock.setPrice(155.0);
googleStock.setPrice(2600.0);
investor1.divestFrom(appleStock);
appleStock.setPrice(160.0);
}
}