C++设计模式4:发布-订阅模式

        主要关注对象的一对多的关系,也就是多个对象都依赖于一个对象,当该对象的状态发生改变时,其他对象都能够接受到相应的通知。

        假如有一个存有数据的对象,这个对象的数据产生了另外三个对象,一个曲线图对象,一个折线图对象,一个圆饼图对象,这时候,如果数据对象发生了改变,那么这三个对象应该及时收到相应的通知。

#include
#include
using namespace std;
class Observer
{
public:
	Observer() {}
	~Observer() {}
	virtual void getmessage(int msg) = 0;
};
class Observer1:public Observer
{
public:
	Observer1() {}
	~Observer1(){}
	void getmessage(int msg)
	{
		switch (msg)
		{
		case 1:
			cout << "Observer1 收到了1信号" << endl;
		case 2:
			cout << "Observer1收到了2信号" << endl;
		default:
			cout << "Observer1不需要的信号" << endl;
		}
	}
};
class Observer2:public Observer
{
public:
	Observer2() {}
	~Observer2() {}
	void getmessage(int msg)
	{
		switch (msg)
		{
		case 2:
			cout << "Observer2 收到了2信号" << endl;
		case 3:
			cout << "Observer2收到了3信号" << endl;
		default:
			cout << "Observer2不需要的信号" << endl;
		}
	}
};
class Observer3:public Observer
{
public:
	Observer3() {}
	~Observer3() {}
	void getmessage(int msg)
	{
		switch (msg)
		{
		case 3:
			cout << "Observer3 收到了3信号" << endl;
		default:
			cout << "Observer3不需要的信号" << endl;
		}
	}
};
class Subject
{
public:
	void addObserver(Observer *observer,int msg)
	{
		subjectmap[msg].push_back(observer);
	}
	void dispatch(int msg)
	{
		auto it = subjectmap.find(msg);
		if (it != subjectmap.end())
		{
			for (auto li : it->second)
			{
				li->getmessage(msg);
			}
		}
	}
private:
	unordered_map>subjectmap;
};
int main()
{
	Subject subject;
	Observer1 *observer1=new Observer1();
	Observer2* observer2 = new Observer2();
	Observer3* observer3 = new Observer3();
	subject.addObserver(observer1, 1);
	subject.addObserver(observer1, 2);
	subject.addObserver(observer1, 3);
	subject.addObserver(observer2, 1);
	subject.addObserver(observer2, 2);
	subject.addObserver(observer2, 3);
	subject.addObserver(observer3, 1);
	subject.addObserver(observer3, 3);
	subject.dispatch(1);
	subject.dispatch(2);
	subject.dispatch(3);
	return 0;
}

C++设计模式4:发布-订阅模式_第1张图片

你可能感兴趣的:(设计模式,c++,设计模式,开发语言,c语言,发布订阅模式,观察者模式,监管者模式)