码迷,mamicode.com
首页 > 其他好文 > 详细

Observer

时间:2014-12-15 13:27:40      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   sp   for   

#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

标签:des   style   blog   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/stanley198610281217/p/4164522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!