C++设计模式4:发布-订阅模式
主要关注对象的一对多的关系,也就是多个对象都依赖于一个对象,当该对象的状态发生改变时,其他对象都能够接受到相应的通知。
假如有一个存有数据的对象,这个对象的数据产生了另外三个对象,一个曲线图对象,一个折线图对象,一个圆饼图对象,这时候,如果数据对象发生了改变,那么这三个对象应该及时收到相应的通知。
#include<iostream>
#include<unordered_map>
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<int, list<Observer*>>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;
}