设计模式<一> 观察者模式

买了本Head First设计模式,可惜里边使用JAVA写的。

对于里边的例子,打算用C++来实现。

第一个例子,观察者模式

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
#include<iostream>
#include<vector>
using namespace std;
//观察者接口
class I_Observer
{
public:
virtual void update(float t,float h,float p) = 0;
};
//显示接口
class I_DispElement
{
public:
virtual void display() = 0;
};
//实例接口
class I_Subject
{
public:
virtual void registerObserver(I_Observer * ob) = 0;
virtual void removeObserver(I_Observer * ob) = 0;
virtual void notifiyObservers() = 0;
};
//观察者实例实现
class CurrentConditionDisp :public I_Observer,public I_DispElement
{
public:
void update(float t, float h, float p)
{
temperature = t;
humidity = h;
pressure = p;
display();
}
void display()
{
cout << "T= " << temperature << endl;
cout << "H= " << humidity << endl;
cout << "P= " << pressure << endl;
}
private:
float temperature;
float humidity;
float pressure;
};
//被观察者实例
class WeatherData :public I_Subject
{
public:
WeatherData()
:temperature(0), humidity(0), pressure(0)
{
}
void registerObserver(I_Observer * ob);
void removeObserver(I_Observer * ob);
void notifiyObservers();
void getTemperature(float t)
{
temperature = t;
}
void getHumidity(float h)
{
humidity = h;
}
void getPressure(float p)
{
pressure = p;
}
void dataChanged()
{
notifiyObservers();
}
private:
vector<I_Observer*> vec;
float temperature;
float humidity;
float pressure;
};
void WeatherData::registerObserver(I_Observer * ob)
{
vec.push_back(ob);
}
void WeatherData::removeObserver(I_Observer * ob)
{
vector<I_Observer*>::iterator it = vec.begin();
while (*it != ob)
it++;
vec.erase(it);
}
void WeatherData::notifiyObservers()
{
vector<I_Observer*>::iterator it = vec.begin();
for (; it != vec.end(); it++)
{
(*it)->update(temperature, humidity, pressure);
}
}
//测试代码
int main(void)
{
WeatherData wd;
CurrentConditionDisp ccd;
wd.getTemperature(2);
wd.getHumidity(3);
wd.getPressure(4);
wd.registerObserver(&ccd);
wd.notifiyObservers();
wd.removeObserver(&ccd);
wd.notifiyObservers();
return 0;
}