观察者模式

观察者模式的UML图如下:

 

这里使用了依赖倒置原则,依赖于抽象,不能依赖于具体实现。底层不能依赖高层。高层是抽象接口,且是相对稳定的。

 

 1 // ConsoleApplication43.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <vector>
 6 #include <algorithm>
 7 #include <iostream>
 8 
 9 using namespace std;
10 
11 class Observer
12 {
13 public:
14     virtual void update(int) = 0;
15 };
16 
17 class Subject
18 {
19 public:
20     void attach(Observer*);
21     void detach(Observer*);
22     void notify();
23     virtual void setState(int)=0;
24     virtual int getState()=0;
25 private:
26     vector<Observer*> vect;
27 protected:
28     int state;
29 };
30 
31 void Subject::attach(Observer* observer)
32 {
33     vect.push_back(observer);
34 }
35 
36 void Subject::detach(Observer* observer)
37 {
38     vector<Observer*>::iterator ite = find(vect.begin(),vect.end(),observer);
39     vect.erase(ite);
40 }
41 
42 void Subject::notify()
43 {
44     vector<Observer*>::iterator begin = vect.begin();
45     while (begin != vect.end())
46     {
47         (*begin)->update(state);
48         ++begin;
49     }
50 }
51 
52 class ConcreteObserver :public Observer
53 {
54     void update(int);
55 };
56 
57 void ConcreteObserver::update(int state)
58 {
59     cout << this << " --->ConcreteObserver---------->" << state << endl;
60 }
61 
62 class ConcreteSubject:public Subject
63 {
64     void setState(int);
65     int getState();
66 };
67 
68 void ConcreteSubject::setState(int st)
69 {
70     state = st;
71 }
72 
73 int ConcreteSubject::getState()
74 {
75     return state;
76 }
77 
78 
79 int main()
80 {
81     Subject *subject = new ConcreteSubject();
82     Observer *ob1 = new ConcreteObserver();
83     Observer *ob2 = new ConcreteObserver();
84     subject->attach(ob1);
85     subject->attach(ob2);
86     subject->setState(1);
87     subject->notify();
88     delete ob1;
89     delete ob2;
90     delete subject;
91     system("pause");
92     return 0;
93 }
View Code

 

posted on 2017-05-05 11:57  ^~~^  阅读(169)  评论(0编辑  收藏  举报

导航