设计模式 - 观察者模式 (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;
}
posted @ 2019-07-23 11:10  Ruohua3kou  阅读(222)  评论(0编辑  收藏  举报