观察者模式,也称发布订阅模式,主题方发布,观察方订阅。
observe.h
/*
*
* Copyright (C) 2023-09-13 14:06 zxinlog <[email protected]>
*
*/
#include <func.h>
#include <iostream>
#include <list>
using std::cout;
using std::endl;
using std::list;
class Observe {
public:
virtual void update(int status) = 0;
};
class Subject {
public:
virtual void attach(Observe *obs) = 0;
virtual void detach(Observe *obs) = 0;
virtual void notify() = 0;
virtual void setStatus(int status) = 0;
virtual int getStatus() = 0;
};
class ConcretSubject : public Subject {
public:
void attach(Observe *obs);
void detach(Observe *obs);
void notify();
void setStatus(int status);
int getStatus();
private:
list<Observe *> _list;
int _status;
};
class ObserveA : public Observe {
void update(int status);
};
class ObserveB : public Observe {
void update(int status);
};
class ObserveC : public Observe {
void update(int status);
};
observe.cc
/*
*
* Copyright (C) 2023-09-13 14:11 zxinlog <[email protected]>
*
*/
#include <func.h>
#include <iostream>
#include <memory>
#include "observe.h"
using std::cout;
using std::endl;
using std::shared_ptr;
void ConcretSubject::attach(Observe *obs) {
_list.push_back(obs);
}
void ConcretSubject::detach(Observe *obs) {
for (auto i = _list.begin(); i != _list.end(); i++) {
if (*i == obs) {
_list.remove(obs);
return;
}
}
}
void ConcretSubject::notify() {
for (std::list<Observe *>::iterator i = _list.begin(); i != _list.end(); i++) {
(*i)->update(_status);
}
}
void ConcretSubject::setStatus(int status) {
_status = status;
}
int ConcretSubject::getStatus() {
return _status;
}
void ObserveA::update(int status) {
cout << "Observe-A"
<< " observe status is " << status << endl;
}
void ObserveB::update(int status) {
cout << "Observe-B"
<< " observe status is " << status << endl;
}
void ObserveC::update(int status) {
cout << "Observe-C"
<< " observe status is " << status << endl;
}
// test
int main() {
shared_ptr<Subject> sub(new ConcretSubject());
shared_ptr<Observe> obA(new ObserveA());
shared_ptr<Observe> obB(new ObserveB());
shared_ptr<Observe> obC(new ObserveC());
sub->setStatus(1);
sub->attach(obA.get());
sub->attach(obB.get());
sub->attach(obC.get());
sub->notify();
sub->detach(obB.get());
sub->setStatus(3);
sub->notify();
}
使用list存储观察者队列信息。
使用attach添加观察者
使用detach删除观察者
使用notify通知观察者更新。