观察者模式实际例子demo

最简单的观察者模式 –

// 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;
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Music 爱好者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值