/*
观察者模式(又叫发布-订阅模式)定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。
这个主题对象在状态发生变化时会通知所有的观察者对象
*/
/*
例子:有员工在上班时间看电影、NBA、股票等与工作无关的内容,前台可以给员工发送通知,因此所有的员工通过监听受监测对象即可对自身的工作做出调整
同样的,老板也需要通知一些业务内容,因此例子主要让在干不同事的员工监听前台类和老板类(继承与subject类),其中subject类维持一个员工对象列表用对于所有员工发出通知
*/
#include<iostream>
#include<string>
#include<list>
using namespace std;
class Observer
{
public:
virtual void Update() = 0;
};
class Subject
{
public:
virtual void Attach(Observer* observer) = 0; //增加和删除员工
virtual void Detach(Observer* observer) = 0;
virtual void Notify() = 0;
virtual string Get() = 0; //获取和设置状态
virtual void Set(const string &s) = 0;
};
class Boss : public Subject
{
private:
//维持一个同事列表
list<Observer*> observers{};
protected:
string action;
public:
virtual void Attach(Observer* observer) //增加和删除员工
{
observers.push_back(observer);
}
virtual void Detach(Observer* observer)
{
observers.remove(observer);
}
virtual void Notify()
{
for (auto o : observers)
{
o->Update();
}
}
virtual string Get() //获取和设置状态
{
return this->action;
}
virtual void Set(const string& s)
{
this->action = s;
}
};
class Xgg : public Subject
{
private:
//维持一个同事列表
list<Observer*> observers;
protected:
string action;
public:
virtual void Attach(Observer* observer) //增加和删除员工
{
observers.push_back(observer);
}
virtual void Detach(Observer* observer)
{
observers.remove(observer);
}
virtual void Notify()
{
for (auto o : observers)
{
o->Update();
}
}
virtual string Get() //获取和设置状态
{
return this->action;
}
virtual void Set(const string& s)
{
this->action = s;
}
};
class StockObserver : public Observer
{
protected:
string name;
Subject *sub;
public:
StockObserver(string name, Subject *sub)
{
this->name = name;
this->sub = sub;
}
public:
virtual void Update()
{
cout << this->sub->Get() << this->name << "关闭股票行情快工作!" << endl;
}
};
class NBAObserver : public Observer
{
protected:
string name;
Subject *sub;
public:
NBAObserver(string name, Subject *sub)
{
this->name = name;
this->sub = sub;
}
public:
virtual void Update()
{
cout << this->sub->Get() << this->name << "关闭NBA快工作!" << endl;
}
};
void Client()
{
Boss *huhansan = new Boss();
StockObserver *tongshi1 = new StockObserver("魏冠茶", huhansan);
NBAObserver * tongshi2 = new NBAObserver("科比", huhansan);
huhansan->Attach(tongshi1);
huhansan->Attach(tongshi2);
huhansan->Set("我胡汉三又回来了");
huhansan->Notify();
huhansan->Detach(tongshi1);
huhansan->Set("下午汇报工作!");
huhansan->Notify();
}
int main()
{
Client();
system("pause");
return 0;
}