首页 > 其他 > 详细

观察者模式

时间:2019-06-08 22:10:30      阅读:108      评论:0      收藏:0      [点我收藏+]

观察者模式常用于事件通知。
observer.h

#pragma once

class IObserver
{
public:
    virtual ~IObserver(){}
    virtual void Doprogress(float percent) = 0;
};

class CObserverProgressBar : public IObserver
{
public:
    virtual ~CObserverProgressBar(){}
    virtual void Doprogress(float percent);
};

class CObserverConsole : public IObserver
{
public:
    virtual ~CObserverConsole(){}
    virtual void Doprogress(float percent);
};

observer.cpp

#include <iostream>
#include "Observer.h"

using namespace std;

void CObserverProgressBar::Doprogress(float percent)
{
    cout << "CObserverProgressBar:" << percent << endl; 
}

void CObserverConsole::Doprogress(float percent)
{
    cout << "CObserverConsole:" << percent << endl; 
}

eventCenter.h

#pragma once
#include <list>
#include "Observer.h"

class CEvent
{
    typedef std::list<IObserver*> OBSERVER_LIST;
    int m_sum;
    int m_dec;
    int m_times;
    OBSERVER_LIST m_observerList;
public:
    CEvent(int sum, int dec);
    virtual ~CEvent(){}
    void addObserver(IObserver* observer);
    void delObserver(IObserver* observer);
    void notify();
};

observer.cpp

#include <iostream>
#include "Observer.h"

using namespace std;

void CObserverProgressBar::Doprogress(float percent)
{
    cout << "CObserverProgressBar:" << percent << endl; 
}

void CObserverConsole::Doprogress(float percent)
{
    cout << "CObserverConsole:" << percent << endl; 
}

main.cpp

#include "EventCenter.h"
#include "Observer.h"

int main()
{
    CObserverProgressBar progrossBar;
    CObserverConsole consol;

    CEvent event(256, 8);
    event.addObserver(&progrossBar);
    event.addObserver(&consol);
    event.notify();

    event.delObserver(&progrossBar);
    event.delObserver(&consol);
    return 0;
}

观察者模式

原文:https://www.cnblogs.com/kuikuitage/p/10991685.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!