观察者模式又叫做发布-订阅模式。观察者模式定义了一种一对多的依赖关系,让多个观察者对象(公司楼上员工)同时监听某一个主题对象(公司1楼前台秘书)。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
1: #include <string>
2: #include <iostream>
3: #include <vector>
4: using namespace std;
5:
6: class SecretaryBase;
7: //抽象观察者
8: class CObserverBase
9: {
10: protected:
11: string name;
12: SecretaryBase* sub;
13: public:
14: CObserverBase(string strname,SecretaryBase* strsub)
15: {
16: name=strname;
17: sub=strsub;
18: }
19: virtual void Update()=0;
20: };
21: //具体的观察者,看股票的
22: class StockObserver : public CObserverBase
23: {
24: public:
25: StockObserver(string strname,SecretaryBase* strsub) : CObserverBase(strname,strsub)
26: {
27: }
28: virtual void Update();
29: };
30:
31: //具体观察者,看NBA的
32: class NBAObserver : public CObserverBase
33: {
34: public:
35: NBAObserver(string strname,SecretaryBase* strsub) : CObserverBase(strname,strsub){}
36: virtual void Update();
37: };
38:
39:
40: //抽象通知者
41: class SecretaryBase
42: {
43: public:
44: string action;
45: vector<CObserverBase*> observers;
46: public:
47: virtual void Attach(CObserverBase* observer)=0;
48: virtual void Notify()=0;
49: };
50:
51: //具体通知者
52: class Secretary :public SecretaryBase
53: {
54: public:
55: void Attach(CObserverBase* ob)
56: {
57: observers.push_back(ob);
58: }
59: void Notify()
60: {
61: vector<CObserverBase*>::iterator p = observers.begin();
62: while (p!=observers.end())
63: {
64: (*p)->Update();
65: p++;
66: }
67: }
68: };
69:
70: void StockObserver::Update()
71: {
72: cout<<name<<":"<<sub->action<<",不要玩股票了,要开始工作了" << endl;
73: }
74: void NBAObserver::Update()
75: {
76: cout<<name<<":"<<sub->action<<",不要玩股票了,要开始工作了" << endl;
77: }
78:
79:
80: 客户端
81: int main()
82: {
83: SecretaryBase *p=new Secretary(); //创建观察者
84: //被观察的对象
85: CObserverBase *s1= new NBAObserver("小李",p);
86: CObserverBase *s2 = new StockObserver("小赵",p);
87: //加入观察队列
88: p->Attach(s1);
89: p->Attach(s2);
90: //事件
91: p->action="老板来了";
92: //通知
93: p->Notify();
94: return 0;
95: }