/*观察者模式:定义对象间一对多的依赖关系,当一个对象的状态发生改变,依赖它的多个对象都要得到通知并自动更新*/
#include <iostream>
#include <memory>
#include <list>
#include <algorithm>
using namespace std;
class Observer { //观察者基类
public:
virtual ~Observer(){}; //基类的析构函数写成虚的,使delete实际指向子类的基类指针时,能先调子类的析构函数,再调基类的。
virtual void update() = 0;
};
class Observed { //被观察者基类
public:
virtual ~Observed(){}
virtual void addObserver(Observer* obs) = 0;
virtual void removeObserver(Observer* obs) = 0;
virtual void notifyObserver() = 0;
};
class DataObserved : public Observed {
public:
~DataObserved()
{
observers.clear();
}
void addObserver(shared_ptr<Observer> obsPtr) override
{
if(find(observers.begin(),observers.end(), obsPtr) == observers.end()){
observers.push_back(obsPtr);
}
}
void removeObserver(shared_ptr<Observer> obsPtr) override
{
for(auto i = observers.begin();i != observers.end();i++){
if((*i) == obsPtr){
observers.erase(i); //容器里存放的智能指针erase后,use_count减1变为0,智能指针指向的堆内存会自动delete
return;
}
}
}
void notifyObserver() override
{
for(auto i = observers.begin();i != observers.end();i++){
(*i)->update();
}
}
private:
vector<shared_ptr<Observer>> observers; //存放观察者对象,当被观察者自身发生改变时通知容器内所有的观察者对象自动更新
};
class TableObserver : public Observer
{
public:
~TableObserver(){cout<<"~~table"<<endl;}
void update() override
{
cout<<"Table update with data."<<endl;
}
};
class ChartObserver : public Observer
{
public:
~ChartObserver(){cout<<"~~chart"<<endl;}
void update() override
{
cout<<"Chart update with data."<<endl;
}
};
int main()
{
shared_ptr<DataObserved> data = make_shared<DataObserved>();
shared_ptr<Observer> table = make_shared<Observer>();
shared_ptr<Observer> chart = make_shared<Observer>();
data->addObserver(table);
data->addObserver(chart);
data->notifyObserver();
data->removeObserver(table);
data->notifyObserver();
return 0;
}
设计模式-观察者模式
于 2021-04-10 01:20:53 首次发布