DesignPattern/20.ObserverPattern/2.Code/Demo.h

78 lines
1.1 KiB
C
Raw Permalink Normal View History

2019-11-06 13:36:28 +00:00
#define __DEMO_H__
#ifdef __DEMO_H__
using namespace std;
#include <list>
2021-10-28 15:15:51 +00:00
// 抽象观察者
2019-11-06 13:36:28 +00:00
class Observer
{
public:
virtual ~Observer() {}
2021-10-28 15:15:51 +00:00
// 声明响应更新方法
2019-11-06 13:36:28 +00:00
virtual void update() = 0;
};
2021-10-28 15:15:51 +00:00
// 具体观察者
class ConcreteObserver : public Observer
2019-11-06 13:36:28 +00:00
{
public:
2021-10-28 15:15:51 +00:00
// 实现响应更新方法
void update()
{
// 具体操作
2019-11-06 13:36:28 +00:00
}
};
2021-10-28 15:15:51 +00:00
// 抽象目标
2019-11-06 13:36:28 +00:00
class Subject
{
public:
virtual ~Subject() {}
2021-10-28 15:15:51 +00:00
// 添加观察者
void attach(Observer *obs)
{
2019-11-06 13:36:28 +00:00
obsList.push_back(obs);
}
2021-10-28 15:15:51 +00:00
// 移除观察者
void detach(Observer *obs)
{
2019-11-06 13:36:28 +00:00
obsList.remove(obs);
}
2021-10-28 15:15:51 +00:00
// 声明通知方法
2019-11-06 13:36:28 +00:00
virtual void notify() = 0;
2021-10-28 15:15:51 +00:00
2019-11-06 13:36:28 +00:00
protected:
2021-10-28 15:15:51 +00:00
// 观察者列表
list<Observer *> obsList;
2019-11-06 13:36:28 +00:00
};
2021-10-28 15:15:51 +00:00
// 具体目标
class ConcreteSubject : public Subject
2019-11-06 13:36:28 +00:00
{
public:
2021-10-28 15:15:51 +00:00
// 实现通知方法
void notify()
{
// 具体操作
// 遍历通知观察者对象
for (int i = 0; i < obsList.size(); i++)
{
2019-11-06 13:36:28 +00:00
obsList[i]->update();
}
}
};
2021-10-28 15:15:51 +00:00
// 客户端代码示例
2019-11-06 13:36:28 +00:00
int main()
{
2021-10-28 15:15:51 +00:00
Subject *sub = new ConcreteSubject();
2019-11-06 13:36:28 +00:00
Observer *obs = new ConcreteObserver();
sub->attach(obs);
sub->notify();
delete sub;
delete obs;
2019-11-06 13:36:28 +00:00
return 0;
}
#endif