-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDS19_Observer.java
More file actions
118 lines (92 loc) · 2.62 KB
/
DS19_Observer.java
File metadata and controls
118 lines (92 loc) · 2.62 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//Subject
import java.util.*;
abstract class Citizen {
ArrayList pols;
String help = "normal";
public void setHelp(String help) {
this.help = help;
}
public String getHelp() {
return this.help;
}
abstract void sendMessage(String help);
public void setPolicemen() {
this.pols = new ArrayList();
}
public void register(Policeman pol) {
this.pols.add(pol);
}
public void unRegister(Policeman pol) {
this.pols.remove(pol);
}
}
//Observer
interface Policeman {
void action(Citizen ci);
}
//ConcreteSubjec
class HuangPuCitizen extends Citizen {
public HuangPuCitizen(Policeman pol) {
setPolicemen();
register(pol);
}
public void sendMessage(String help) {
setHelp(help);
for(int i = 0; i < pols.size(); i++) {
Policeman pol = (Policeman)pols.get(i);
//通知警察行动
pol.action(this);
}
}
}
class TianHeCitizen extends Citizen {
public TianHeCitizen(Policeman pol) {
setPolicemen();
register(pol);
}
public void sendMessage(String help) {
setHelp(help);
for (int i = 0; i < pols.size(); i++) {
Policeman pol = (Policeman)pols.get(i);
//通知警察行动
pol.action(this);
}
}
}
//ConcreteObserver
class HuangPuPoliceman implements Policeman {
public void action(Citizen ci) {
String help = ci.getHelp();
if (help.equals("normal")) {
System.out.println("一切正常, 不用出动");
}
if (help.equals("unnormal")) {
System.out.println("有犯罪行为, 黄埔警察出动!");
}
}
}
class TianHePoliceman implements Policeman {
public void action(Citizen ci) {
String help = ci.getHelp();
if (help.equals("normal")) {
System.out.println("一切正常, 不用出动");
}
if (help.equals("unnormal")) {
System.out.println("有犯罪行为, 天河警察出动!");
}
}
}
public class DS19_Observer{
public static void main(String[] args) {
Policeman thPol = new TianHePoliceman();
Policeman hpPol = new HuangPuPoliceman();
Citizen citizen = new HuangPuCitizen(hpPol);
citizen.register(thPol);
citizen.sendMessage("unnormal");
citizen.sendMessage("normal");
System.out.println("===========");
citizen = new TianHeCitizen(thPol);
citizen.sendMessage("normal");
citizen.sendMessage("unnormal");
}
}