//观察者模式,
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class AbstractBoss;
class AbstractWorker
{
public:
virtual void update() = 0;
};
class StockWorker:public AbstractWorker
{
AbstractBoss* m_boss;
string m_name;
public:
StockWorker(string name, AbstractBoss* boss) :m_name(name), m_boss(boss) {};
void update();
};
class NBAworker :public AbstractWorker
{
AbstractBoss* m_boss;
string m_name;
public:
NBAworker(string name, AbstractBoss* boss) :m_name(name), m_boss(boss) {};
void update();
};
class AbstractBoss
{
public:
virtual string getaction() = 0;
virtual void Notify() = 0;
};
class Boss :public AbstractBoss
{
vector<AbstractWorker*> abs;
string action;
public:
void Addabs(AbstractWorker* temp)
{
abs.push_back(temp);
}
void setaction(string value) { action = value; }
string getaction() { return action; }
void Notify()
{
for (int i = 0; i < abs.size(); i++)
abs[i]->update();
}
};
void StockWorker::update()
{
cout << m_boss->getaction() << " " << m_name << " 关闭股票行情,继续工作!" << endl;
}
void NBAWorker::update()
{
cout << m_boss->getaction() << " " << m_name << " 关闭NBA直播,继续工作!" << endl;
}
int main()
{
Boss* boss = new Boss;
StockWorker* swer = new StockWorker("xiaowang", boss);
NBAWorker* Nwer = new NBAWorker("小李",boss);
boss->Addabs(swer);
boss->Addabs(Nwer);
boss->setaction("laobanhuilaile");
boss->Notify();
system("pause");
return 0;
}
运行结果为:
laobanhuilaile xiaowang 关闭股票行情,继续工作!
laobanhuilaile 小李 关闭NBA直播,继续工作!
请按任意键继续. . .