观察者模式常用于事件通知。
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