Chinaunix首页 | 论坛 | 博客
  • 博客访问: 41396
  • 博文数量: 17
  • 博客积分: 1432
  • 博客等级: 上尉
  • 技术积分: 165
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-27 09:38
文章分类

全部博文(17)

文章存档

2011年(1)

2009年(16)

最近访客

分类: C/C++

2009-02-24 19:32:23

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

class Observer
{
public:
    virtual void Update() = 0;
};

class Subject
{
private:
    list<Observer*> m_list_observer;

public:
    virtual void Attach(Observer* observer)
    {
        m_list_observer.push_back(observer);
    }

    virtual void Detach(Observer* observer)
    {
        m_list_observer.remove(observer);
    }

    virtual void Notify()
    {
        list<Observer*>::iterator list_it;
        for(list_it = m_list_observer.begin();list_it != m_list_observer.end();list_it++)
        {
            (*list_it)->Update();
        }
    }
};

class ConcreateSubject :public Subject
{
private:
    string m_str_SubjectState;

public:
    virtual string GetSubjectState(void)
    {
        return m_str_SubjectState;
    }

    virtual void SetSubjectState(string SubjectState)
    {
        m_str_SubjectState = SubjectState;
    }
};

class ConcreateObserver : public Observer
{
private:
    string m_str_name;
    string m_str_SubjectState;
    ConcreateSubject* m_Subject;

public:
    ConcreateObserver(ConcreateSubject* subject , string name)
    {
        m_Subject = subject;
        m_str_name = name;
    }

    void Update()
    {
        m_str_SubjectState = m_Subject->GetSubjectState();
        cout<<"观察者"<<m_str_name<<"的新状态是"<<m_str_SubjectState<<endl;
    }

    ConcreateSubject* GetSubject(void)
    {
        return m_Subject;
    }

    void SetSubject(ConcreateSubject* subject)
    {
        m_Subject = subject;
    }
};

int main(void)
{
    ConcreateSubject* s = new ConcreateSubject();

    ConcreateObserver* ob1 = new ConcreateObserver(s , "x");
    s->Attach(ob1);
    s->Attach(new ConcreateObserver(s , "y"));
    s->Attach(new ConcreateObserver(s , "z"));

    s->SetSubjectState("ABC");
    s->Notify();

    cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;

    s->Detach(ob1);
    s->SetSubjectState("DEF");
    s->Notify();
};

阅读(1063) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~