设计模式---观察者模式(恐怖袭击、地震的例子,有类关系图)

设计模式---观察者模式(恐怖袭击、地震的例子,有类关系图)

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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
internal interface Warning
{
String Situation { get; set; }
void Warn();
void Add(PeopleInSchool p);
void Sub(PeopleInSchool p);
}

class PoliceStation : Warning
{
private IList<PeopleInSchool> field = new List<PeopleInSchool>();
string situation;

public string Situation
{
get { return situation; }
set { situation = value; }
}

public void Warn()
{
foreach (PeopleInSchool p in field)
{
p.WarningReceived();
}
}

public void Add(PeopleInSchool p)
{
field.Add(p);
}

public void Sub(PeopleInSchool p)
{
field.Remove(p);
}
}

class EarthquakeDepartment : Warning
{
string situation;
private IList<PeopleInSchool> field = new List<PeopleInSchool>();

public string Situation
{
get { return situation; }
set { situation = value; }
}

public void Warn()
{
foreach (PeopleInSchool p in field)
{
p.WarningReceived();
}
}

public void Add(PeopleInSchool p)
{
field.Add(p);
}

public void Sub(PeopleInSchool p)
{
field.Remove(p);
}
}

abstract class PeopleInSchool
{
protected Warning field;

public PeopleInSchool(Warning w)
{
field = w;
}

public abstract void WarningReceived();
}

class Teacher : PeopleInSchool
{
public Teacher(Warning w)
: base(w)
{
}

public override void WarningReceived()
{
Console.WriteLine("我是老师" + field.Situation);
}
}

class Student : PeopleInSchool
{
public Student(Warning w)
: base(w)
{
}

public override void WarningReceived()
{
Console.WriteLine("我是学生" + field.Situation);
}
}

class Client
{
public static void Main()
{
PoliceStation p = new PoliceStation();
Teacher t = new Teacher(p);
Student s = new Student(p);
p.Add(t);
p.Add(s);
p.Situation = "有恐怖袭击!!!";
p.Warn();
p.Situation = "注意防火防盗!!!";
p.Warn();
EarthquakeDepartment e = new EarthquakeDepartment();
t = new Teacher(e);
s = new Student(e);
e.Add(t);
e.Add(s);
e.Situation = "要地震了!!!";
e.Warn();
Console.Read();
}
}
}