- 行为型模式:主要关注的是对象之间的通信
- 观察者-监听者模式(发布-订阅)模式:主要关注的是对象一对多的关系
- 也就是说多个对象都依赖一个对象,当该对象的状态发生改变时,其他对象都能接收到相应通知
class Observer
{
public:
Observer() { cout << "Observer构造" << endl; }
virtual ~Observer() { cout << "Observer析构" << endl; }
//处理消息的接口
virtual void handle(int msgID) = 0;
};
class Subject
{
public:
Subject() {
cout << "Subject的构造函数" << endl;
}
~Subject() {
cout << "Subject的析构函数" << endl;
}
//给主题增加观察者对象
void addObserver(Observer* observer,int msgID) {
obseverMap_[msgID].push_back(observer);
/*auto it = obseverMap_.find(msgID);
if (it != obseverMap_.end()) {
it->second.push_back(observer);
}
else {
list<Observer*>list;
list.push_back(observer);
obseverMap_.insert({ msgID, list });
}
*/
}
void remove(Observer* observer) {
}
//主题发生改变,通知相应的观察者对象处理事件
void dispatch(int msgID) {
auto it = obseverMap_.find(msgID);
if (it != obseverMap_.end()) {
for (Observer* pObserver : it->second) {
pObserver->handle(msgID);
}
}
}
private:
unordered_map<int,list<Observer*>> obseverMap_;
};
class Observer1:public Observer
{
public:
Observer1(){
cout << "Observer1构造" << endl;
}
~Observer1() {
cout << "Observer1析构" << endl;
}
void handle(int msgID) {
switch (msgID)
{
case 1:
cout << "Observer1 recv 1 msg!" << endl;
break;
case 2:
cout << "Observer1 recv 2 msg!" << endl;
break;
default:
cout << "Observer1 recv unkonwn msg!" << endl;
break;
}
}
};
//观察者2
class Observer2 :public Observer
{
public:
Observer2() {
cout << "Observer2构造" << endl;
}
~Observer2() {
cout << "Observer2析构" << endl;
}
void handle(int msgID) {
switch (msgID)
{
case 2:
cout << "Observer2 recv 2 msg!" << endl;
break;
default:
cout << "Observer2 recv unkonwn msg!" << endl;
break;
}
}
};
/观察者3
class Observer3 :public Observer
{
public:
Observer3() {
cout << "Observer3构造" << endl;
}
~Observer3() {
cout << "Observer3析构" << endl;
}
void handle(int msgID) {
switch (msgID)
{
case 1:
cout << "Observer3 recv 1 msg!" << endl;
break;
case 3:
cout << "Observer3 recv 3 msg!" << endl;
break;
default:
cout << "Observer3 recv unkonwn msg!" << endl;
break;
}
}
};
int main()
{
Subject subject;
Observer* p1 = new Observer1;
Observer* p2 = new Observer2;
Observer* p3 = new Observer3;
subject.addObserver(p1, 1);
subject.addObserver(p1, 2);
subject.addObserver(p2, 2);
subject.addObserver(p3, 3);
subject.addObserver(p3, 1);
int msgid = 0;
int conut = 0;
for (;;) {
cout << "请输入消息ID:";
cin >> msgid;
if (msgid == -1)
break;
subject.dispatch(msgid);
conut++;
}
delete p1;
p1 = nullptr;
delete p2;
p2 = nullptr;
delete p3;
p3 = nullptr;
return 0;
}
优点:
- 观察者和被观察者之间建立了一个抽象的耦合。
- 观察者模式支持广播通信
缺点:
- 观察者之间有过多的细节依赖、提高时间消耗及程序的复杂度。
- 如果在观察者和观察目标之间存在循环依赖,观察目标会触发它们之间进行循环调用,可能导致系统崩溃。