-
Notifications
You must be signed in to change notification settings - Fork 1
/
observer.java
95 lines (74 loc) · 1.93 KB
/
observer.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
import java.util.ArrayList;
import java.util.List;
interface Notifier {
void notifyObserver();
void attach(Observer observer);
void detach(Observer observer);
void stateChange();
}
interface Observer {
void update();
}
class AbstractNotifier implements Notifier {
private List<Observer> list = new ArrayList<>();
private String state;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public void notifyObserver() {
for(Observer observer : list)
observer.update();
}
@Override
public void attach(Observer observer) {
list.add(observer);
}
@Override
public void detach(Observer observer) {
list.remove(observer);
}
@Override
public void stateChange() {
}
}
class Secretary extends AbstractNotifier {
@Override
public void stateChange(){
setState("大家,老闆在門口了!");
}
}
class Boss extends AbstractNotifier {
@Override
public void stateChange(){
setState("大家,老闆我回來了!好久不見!");
}
}
class StockObserver implements Observer {
@Override
public void update() {
System.out.println("趕快關閉股票網頁,回去工作!");
}
}
class NBAObserver implements Observer {
@Override
public void update() {
System.out.println("趕快關閉NBA網頁,回去工作");
}
}
public class Main {
public static void main(String[] args){
Notifier notifier = new Boss();
Observer stockObserver = new StockObserver();
Observer NBAObserver = new NBAObserver();
notifier.attach(stockObserver);
notifier.attach(NBAObserver);
/* 看股票的觀察者,沒有被老闆通知到 */
notifier.detach(stockObserver);
notifier.stateChange();
notifier.notifyObserver();
}
}