首页 > 代码库 > Observer
Observer
#include <iostream>#include <list>using namespace std;#define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; }class Observer{public: virtual void Update(string sSubjectAttr)=0;};class ConcreteObserverA : public Observer{public: ConcreteObserverA() {} ~ConcreteObserverA() {} void Update(string sSubjectAttr) { cout<<"ConcreteObserverA::Udate accoring to ["<<sSubjectAttr<<"]"<<endl; }};class ConcreteObserverB : public Observer{public: ConcreteObserverB() {} ~ConcreteObserverB() {} void Update(string sSubjectAttr) { cout<<"ConcreteObserverB::Udate accoring to ["<<sSubjectAttr<<"]"<<endl; }};class ConcreteObserverC : public Observer{public: ConcreteObserverC() {} ~ConcreteObserverC() {} void Update(string sSubjectAttr) { cout<<"ConcreteObserverC::Udate accoring to ["<<sSubjectAttr<<"]"<<endl; }};class Subject{public: Subject() {} ~Subject(); void AddObserver(Observer* pObserver) { m_observerList.push_back(pObserver); } void SetAttr(string sAttr); private: list<Observer*> m_observerList;};Subject::~Subject(){ list<Observer*>::iterator iter; for (iter = m_observerList.begin(); iter != m_observerList.end(); iter++) { Observer* pTemp = *iter; DESTROY_POINTER(pTemp); } m_observerList.clear();}void Subject::SetAttr(string sAttr){ list<Observer*>::iterator iter; for (iter = m_observerList.begin(); iter != m_observerList.end(); iter++) { (*iter)->Update(sAttr); }}int main(int argc, char *argv[]){ Subject subject; subject.AddObserver(new ConcreteObserverA); subject.AddObserver(new ConcreteObserverB); subject.AddObserver(new ConcreteObserverC); subject.SetAttr("Attr add"); subject.SetAttr("Attr remove"); return 0;}
Observer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。