观察者模式

Observer.h

#ifndef _OBSERVER_H_
#define _OBSERVER_H_
#include <string>
#include <iostream>
#include <list>
class ConcreteSubject;
//抽象观察者
class Observer
{
public:
    /**
     *@brief 更新接口
     */
    virtual void Update() = 0;
};

//具体观察者
class ConcreteObserver: public Observer
{
public:
    ConcreteObserver(std::string name, ConcreteSubject* sub)
    {
        m_name = name;
        m_subject = sub;
    }

    //前台通知函数
    virtual void Update();


private:
    std::string            m_name;
    std::string            m_observerState;
    ConcreteSubject*    m_subject;    //保存具体主题对象的指针,在更新时获取主题状态
    
};

#endif

SubObject.h

#ifndef _SECREATRY_H_
#define _SECREATRY_H_
#include <list>
#include <string>
class Observer;
/**
 *@brief 抽象通知者类
 */
class Subject
{
public:
    /**
     *@brief 增加观察者
     */
    virtual void Attach(Observer* pObserver)
    {
        m_pObservers.push_back(pObserver);
    }
    /**
     *@brief 减少观察者
     */
    virtual void Detach(Observer* pObserver)
    {
        m_pObservers.remove(pObserver);
    }
    /**
     *@brief 通知观察者
     */
    virtual void Notify()
    {
        for (auto pObserver : m_pObservers)
        {
            pObserver->Update();
        }
    }
private:
    std::list<Observer*> m_pObservers;//所有观察者

};

/**
 *@brief 具体通知者
 */
class ConcreteSubject : public Subject
{
private:
    std::string                    m_subjectState;            //被观察者观察的对象
public:
    void SetState(const std::string& state)
    {
        m_subjectState = state;
    }
    const std::string& GetState()
    {
        return m_subjectState;
    }
};
#endif

Observer.cpp

#include "Observer.h"
#include "SubObject.h"
void ConcreteObserver::Update()
{
    m_observerState = m_subject->GetState();
    std::cout << "观察者" << m_name << "新状态是" << m_observerState << std::endl;
}

Main.cpp

#include "Observer.h"
#include "SubObject.h"
/*
将系统分割成相互协作的类有不好的副作用,需要维护对象间的一致性,各类之间高度耦合,给维护和扩展带来不便

*/
int main()
{
    ConcreteSubject* pSub = new ConcreteSubject;

    ConcreteObserver ob1("zz", pSub);
    ConcreteObserver ob2("zss", pSub);

    pSub->Attach(&ob1);
    pSub->Attach(&ob2);
    pSub->SetState("吃饭了");
    pSub->Notify();

    getchar();
    return 0;
}

 

posted @ 2015-03-22 11:14  zzyoucan  阅读(201)  评论(0编辑  收藏  举报