设计模式 - 观察者模式 (C++实现)

在这里插入图片描述

#include <iostream>
#include <list>
#include <string>
using namespace std;
class ISubject;
class IObserver;
class Subject;
class Observer;


class ISubject {
private:
	list<IObserver*> observerList;
public:
	void AddObserver(IObserver *obs) {
		observerList.push_back(obs);
	};
	void RemoveObserver(IObserver *obs) {
		observerList.remove(obs);
	};
	virtual void Notified(IObserver *) = 0;

	void Update() {
		for (auto ob : observerList)
		{
			if (ob != NULL) {
				Notified(ob);
			}
		}
	}
};

class IObserver {
public:
	virtual void Received(ISubject *) = 0;
};

// 实例:发布者
class Subject :public ISubject
{
public:
	Subject() :ISubject() {	};
	void Notified(IObserver *obs) {
		obs->Received(this);
	}
};

// 实例:接收(观察)者
class Observer :public IObserver
{
public:
	Observer(string& n) {
		name = n;
	};
	void Received(ISubject *sub) {
		cout << "this is " + name + " OBer, Received.\n";
	}
private:
	string name;
};

int main() {
	string val = "1";
	Observer *obs1 = new Observer(val);
	val = "2";
	Observer *obs2 = new Observer(val);
	val = "3";
	Observer *obs3 = new Observer(val);

	Subject *sub = new Subject();

	// 订阅消息
	sub->AddObserver(obs1);
	sub->AddObserver(obs2);
	sub->AddObserver(obs3);

	// 发布消息
	sub->Update();
	cout << "///\n";
	sub->RemoveObserver(obs2);
	sub->Update();
	cout << "///\n";

	/*
	this is 1 OBer, Received.
	this is 2 OBer, Received.
	this is 3 OBer, Received.
	///
	this is 1 OBer, Received.
	this is 3 OBer, Received.
	///
	*/
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值