观察者模式

抽象主题(Subject):它把所有观察者对象的引用保存到一个聚集里,每个主题都可以有任何数量的观察者。抽象主题提供一个接口,可以增加和删除观察者对象。

具体主题(ConcreteSubject):将有关状态存入具体观察者对象;在具体主题内部状态改变时,给所有登记过的观察者发出通知。

抽象观察者(Observer):为所有的具体观察者定义一个接口,在得到主题通知时更新自己。

具体观察者(ConcreteObserver):实现抽象观察者角色所要求的更新接口,以便使本身的状态与主题状态协调。

 

// Observer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <string>
#include <list>
using namespace std;

class Watcher{                   //小伙伴们准备接收前台小姐的通知,偷懒变成积极状态,观察者
public:
    virtual void update() = 0;  //接收到主题角色的通知后,所做动作
  virtual ~Watcher(){}
}; class Watched{ //主题角色,向众小伙伴发送通知老板来了 public: virtual void addWatcher(Watcher * pwathcer) = 0; virtual void removeWatcher(Watcher * pwatcher) = 0; virtual void notifyAll() = 0; virtual ~Watched() {} protected: list< Watcher * > m_list; }; class ConcreateWatcher:public Watcher{ public: void update(){ cout<<"from fun to active"<<endl; } }; class ConcreateWatched:public Watched{ public: void addWatcher(Watcher * pwathcer){ m_list.push_back(pwathcer); } void removeWatcher(Watcher * pwatcher){ m_list.remove(pwatcher); } void notifyAll(){ list< Watcher *>::iterator it= m_list.begin(); while(it != m_list.end()){ (*it)->update(); ++it; } } ~ConcreateWatched(){ list< Watcher *>::iterator it= m_list.begin(); while(it != m_list.end()){ delete *it; ++it; } } }; int main(int argc, char* argv[]) { Watched * phaoren = new ConcreateWatched; Watcher * pdiaosi1 = new ConcreateWatcher; Watcher * pdiaosi2 = new ConcreateWatcher; Watcher * pdiaosi3 = new ConcreateWatcher; phaoren->addWatcher(pdiaosi1); phaoren->addWatcher(pdiaosi2); phaoren->addWatcher(pdiaosi3); phaoren->notifyAll();
   delete phaoren; //diaosi们,在主题角色的析构函数中释放
return 0; }

 

posted @ 2015-07-17 20:27  朽木可雕否  阅读(192)  评论(0编辑  收藏  举报