目录
1.观察者模式
观察者模式:定义一种 一(被观察)对多 (观察)的关系。在被观察类发生某种事件时,观察类需要做出反应。
实现方式:
在被观察者类里定义一个表示状态的变量,然后在观察者类里存放一个被观察者类对象,通过被观察者类对象获取状态。同时,被观察者类使用vector/list .... 来管理观察者。
2.看看代码吧
cpp
#include <iostream>
#include <string>
#include <list>
using namespace std;
//观察者类
class Observer {
public:
Observer() {}
virtual ~Observer() {}
virtual void update() {}
};
class SubObject
{
public:
string _action; //设置状态
SubObject() {}
virtual ~SubObject() {}
//添加观察者
void attach(Observer* ob)
{
ls.push_back(ob);
}
//去除观察者
void detach(Observer* ob)
{
ls.remove(ob);
}
//通知
void notify()
{
for (auto e : ls)
{
e->update();
}
}
//设置状态
virtual void SetAction(string action) {
_action = action;
}
//返回状态
virtual string GetAction() {
return _action;
}
protected:
list<Observer*> ls;
};
class BossObject : public SubObject
{
public:
BossObject()
{}
void SetAction(string action) {
_action = action;
}
string GetAction() {
return _action;
}
};
class SleepObserver : public Observer
{
public:
SleepObserver(string name, SubObject* sub)
:_sub(sub), _name(name)
{}
void update()
{
string action = _sub->GetAction();
cout << "我是观察者: " << _name << endl;
cout << "老板说:" << action << endl;
if (action == "sleep")
cout << "我要睡大觉咯" << endl;
}
private:
SubObject* _sub;
string _name;
};
class WorkObserver : public Observer
{
public:
WorkObserver(string name, SubObject* sub)
:_sub(sub), _name(name)
{}
void update()
{
string action = _sub->GetAction();
cout << "我是观察者: " << _name << endl;
cout << "老板说:" << action << endl;
if (action == "work")
cout << "我要努力加班,努力搞$" << endl;
}
private:
SubObject* _sub;
string _name;
};
int main()
{
SubObject* Boss = new BossObject();
SleepObserver* ob1 = new SleepObserver("sleepob", Boss);
WorkObserver* ob2 = new WorkObserver("workob", Boss);
Boss->attach(ob1);
Boss->attach(ob2);
Boss->SetAction("work");
Boss->notify();
cout << endl;
Boss->SetAction("sleep");
Boss->notify();
cout << endl;
return 0;
}
结果图: