皇帝后宫佳丽三千,每天晚上啪啪啪,被临幸前要沐浴更衣,等待啪啪啪。后宫佳丽三千总不能全都每天准时沐浴更衣等待被临幸吧,因此皇帝就要提前通知要被临幸的美女,被临幸的美女就化化妆啦之类的。
这三千佳丽就相当于观察者,等待皇帝临幸的通知,根据临幸通知做出相应的对策。而皇帝相当于发布者,发布临幸的目标。这就是简单的观察者-发布者设计模式。
代码:
代码并不规范,有些该加锁的地方没加,不过不影响理解。
#ifndef _MAIN_H_ #define _MAIN_H_ #include <iostream> #include <set> using namespace std; class Observer; class Subject { public: explicit Subject() {} virtual ~Subject() { set<Observer*>::iterator iter = observer_set_.begin(); for (; iter != observer_set_.end(); ++iter) { if (*iter) { delete(*iter); } } observer_set_.clear(); } private: explicit Subject(const Subject&) {} Subject& operator = (const Subject&) {} public: virtual int RegistryObserver(Observer* obj) = 0; virtual int RemoveObserver(Observer* obj) = 0; virtual int NotifyEvent(int flag) = 0; protected: set<Observer*> observer_set_; }; class Observer { public: explicit Observer() {} Observer(Subject* sbj) : subject_(sbj) {} virtual ~Observer() { if (subject_) { delete subject_; subject_ = NULL; } } private: explicit Observer(const Observer&) {} Observer& operator = (const Observer&) {} public: virtual int HandleEvent(int flag) = 0; protected: Subject* subject_; }; class EmperorSubject : public Subject { public: explicit EmperorSubject() {} virtual ~EmperorSubject() {} private: explicit EmperorSubject(const EmperorSubject&) {} EmperorSubject& operator = (const EmperorSubject&) {} public: int RegistryObserver(Observer* obj) { observer_set_.insert(obj); return 0; } int RemoveObserver(Observer* obj) { set<Observer*>::iterator iter = observer_set_.find(obj); if (iter != observer_set_.end()) { observer_set_.erase(iter); } return 0; } int NotifyEvent(int flag) { set<Observer*>::iterator iter = observer_set_.begin(); for(; iter != observer_set_.end(); ++iter) { (*iter)->HandleEvent(flag); } return 0; } }; class Consubine1 : public Observer { public: explicit Consubine1() {} Consubine1(Subject* sbj) { subject_ = sbj; } virtual ~Consubine1() {} private: explicit Consubine1(const Consubine1&) {} Consubine1& operator = (const Consubine1&) {} public: int HandleEvent(int flag) { if (flag == 1) { cout << "i am Consubine1 , i want aaa" << endl; } } }; class Consubine2 : public Observer { public: explicit Consubine2() {} Consubine2(Subject* sbj) { subject_ = sbj; } virtual ~Consubine2() {} private: explicit Consubine2(const Consubine2&) {} Consubine2& operator = (const Consubine2&) {} public: int HandleEvent(int flag) { if (flag == 2) { cout << "i am Consubine2 , i want aaa" << endl; } } }; #endif
#include "main.h" int main(int argc, char* argv[]) { Subject* sbj = new EmperorSubject(); Observer* obj1 = new Consubine1(sbj); Observer* obj2 = new Consubine2(sbj); sbj->RegistryObserver(obj1); sbj->RegistryObserver(obj2); sbj->NotifyEvent(1); }
以上就是观察者模式
优点:
皇帝不需要知道每位嫔妃为他临幸怎么准备的,也没必要
2. 皇帝的嫔妃太多了,有些可能中途死掉了,有些可能皇帝临时抢过来的,皇帝也记不住也不想管,只需要由嫔妃自己过来注册即可(相当于到翻牌子的太监那把牌子清楚或者增加)
原文:http://my.oschina.net/hejiula/blog/291656