1.定义
在GOF的《设计模式:可复用面向对象软件的基础》一书中对观察者模式是这样说的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
2.代码简单实现
1 #include2 #include 3 #include 4 using namespace std; 5 class AbObserver 6 { 7 public: 8 virtual void getMessage(string message) = 0; 9 };10 11 class AbSecretary12 {13 public:14 virtual void senfMessage(string message) = 0;15 virtual void addObserver(AbObserver * observer) = 0;16 };17 //开小差的同事类(观察者)18 class Observer:public AbObserver19 {20 public:21 void getMessage(string message)22 {23 cout << message << endl;24 }25 };26 //秘书类(主题对象,通知者)27 class Secretary:public AbSecretary28 {29 public:30 void senfMessage(string message)31 {32 for (list
::iterator it = observers.begin(); it != observers.end(); it++)33 {34 (*it)->getMessage(message);35 }36 }37 void addObserver(AbObserver * observer)38 {39 observers.push_back(observer);40 }41 private:42 list observers;43 };44 45 int main()46 {47 Observer *observer1 = new Observer;48 Observer *observer2 = new Observer;49 Secretary * secretary = new Secretary;50 secretary->addObserver(observer1);51 secretary->addObserver(observer2);52 secretary->senfMessage("老板来了");53 secretary->senfMessage("老板走了");54 system("pause");55 return 0;56 }