最简单的观察者模式 –
// Watcher.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <algorithm>
using namespace std;
// 观察者抽象类
class IObserver {
public:
// 更新
virtual void Update(std::string& str) = 0;
};
// 英雄观察类
class CHero :public IObserver
{
public:
CHero()
{
cout << "英雄创建" << endl;
}
~CHero()
{
cout << "英雄销毁" << endl;
}
void Update(std::string& str)
{
cout << "英雄界面的金币数量:" << str << endl;
}
};
// UI类
class CUI :public IObserver
{
public:
CUI()
{
cout << "UI创建" << endl;
}
~CUI()
{
cout << "UI销毁" << endl;
}
void Update(std::string& str)
{
cout << "UI界面的金币数量:" << str << endl;
}
};
// 目标类抽象类
class ISubject
{
public:
virtual void Attach(IObserver* ) = 0;
virtual void Detach(IObserver*) = 0;
virtual void Notify() = 0;
};
// 金币类
class CGoldMoney :ISubject
{
public:
CGoldMoney()
{
cout << "金币初始化" << endl;
}
~CGoldMoney() {
cout << "金币销毁" << endl;
}
void Attach(IObserver* pObserver)
{
m_pVecObserver.push_back(pObserver);
}
void Detach(IObserver* pObserver)
{
for (vector<IObserver*>::iterator it = m_pVecObserver.begin(); it != m_pVecObserver.end(); )
{
if (*it == pObserver)
{
it = m_pVecObserver.erase(it);
break;
}
else
{
++it;
}
}
}
void SetMoney(std::string& str)
{
m_strMoney = str;
}
void Notify()
{
for (int i = 0; i < m_pVecObserver.size(); i++)
{
m_pVecObserver[i]->Update(m_strMoney);
}
}
private:
std::vector<IObserver*> m_pVecObserver;
std::string m_strMoney; // 金币数量
};
void TestWatchMode()
{
std::unique_ptr<CGoldMoney> pGoldMoney(new CGoldMoney());
std::unique_ptr<CHero> pHero(new CHero());
std::unique_ptr<CUI> pUI(new CUI());
pGoldMoney->Attach(pHero.get());
pGoldMoney->Attach(pUI.get());
std::string strMoney = "70元";
pGoldMoney->SetMoney(strMoney);
pGoldMoney->Notify();
cout << "--------------------------重新通知测试-----------------------------------------" << endl;
std::unique_ptr<CHero> pCurHero(new CHero());
pGoldMoney->Detach(pUI.get());
pGoldMoney->Attach(pCurHero.get());
strMoney = "100元";
pGoldMoney->SetMoney(strMoney);
pGoldMoney->Notify();
cout << "--------------------------End-----------------------------------------" << endl;
}
int main()
{
TestWatchMode();
system("pause");
return 0;
}
运行结果: