首页 > 代码库 > 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