标签:style blog http color os io ar art div
【1】什么是观察者模式?
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。
这个主题对象在状态上发生变化时,会通知所有观察者对象,让他们能够自动更新自己
【2】观察者模式代码示例:
代码示例如下:
1 #include <iostream> 2 #include <string> 3 #include <list> 4 using namespace std; 5 6 class Observer; 7 8 class Subject 9 { 10 protected: 11 list<Observer*> observers; 12 public: 13 string action; 14 public: 15 virtual void attach(Observer*) = 0; 16 virtual void detach(Observer*) = 0; 17 virtual void notify() = 0; 18 }; 19 20 class Observer 21 { 22 protected: 23 string name; 24 Subject *sub; 25 public: 26 Observer(string name, Subject *sub) 27 { 28 this->name = name; 29 this->sub = sub; 30 } 31 string getName() 32 { 33 return name; 34 } 35 virtual void update() = 0; 36 }; 37 38 class StockObserver : public Observer 39 { 40 public: 41 StockObserver(string name, Subject *sub) : Observer(name, sub) 42 { 43 } 44 void update(); 45 }; 46 47 void StockObserver::update() 48 { 49 cout << name << " 收到消息:" << sub->action << endl; 50 if (sub->action == "梁所长来了!") 51 { 52 cout << "我马上关闭股票,装做很认真工作的样子!" << endl; 53 } 54 } 55 56 class NBAObserver : public Observer 57 { 58 public: 59 NBAObserver(string name, Subject *sub) : Observer(name, sub) 60 { 61 } 62 void update(); 63 }; 64 65 void NBAObserver::update() 66 { 67 cout << name << " 收到消息:" << sub->action << endl; 68 if (sub->action == "梁所长来了!") 69 { 70 cout << "我马上关闭NBA,装做很认真工作的样子!" << endl; 71 } 72 } 73 74 class Secretary : public Subject 75 { 76 void attach(Observer *observer) 77 { 78 observers.push_back(observer); 79 } 80 void detach(Observer *observer) 81 { 82 list<Observer *>::iterator iter = observers.begin(); 83 while (iter != observers.end()) 84 { 85 if ((*iter) == observer) 86 { 87 cout << "erase:" << observer->getName() << endl; 88 observers.erase(iter++); 89 } 90 else 91 { 92 ++iter; 93 } 94 } 95 } 96 void notify() 97 { 98 list<Observer *>::iterator iter = observers.begin(); 99 while (iter != observers.end()) 100 { 101 (*iter)->update(); 102 ++iter; 103 } 104 } 105 }; 106 107 108 int main() 109 { 110 Subject *dwq = new Secretary(); 111 112 Observer *xs = new NBAObserver("xiaoshuai", dwq); 113 Observer *zy = new NBAObserver("zouyue", dwq); 114 Observer *lm = new StockObserver("limin", dwq); 115 116 dwq->attach(xs); 117 dwq->attach(zy); 118 dwq->attach(lm); 119 120 dwq->action = "去吃饭了!"; 121 dwq->notify(); 122 cout << endl; 123 124 dwq->action = "梁所长来了!"; 125 dwq->notify(); 126 127 dwq->detach(lm); 128 dwq->detach(zy); 129 dwq->detach(xs); 130 131 return 0; 132 }
Good Good Study, Day Day Up.
顺序 选择 循环 总结
标签:style blog http color os io ar art div
原文地址:http://www.cnblogs.com/Braveliu/p/3946750.html