观察者模式
#include <iostream>
#include <cmath>
#include <list>
/**
* @brief 组件协作-观察者模式
* 多个observer对一个subject进行观测,当一个subject某些状态改变之后,
* 通知多个observer,然后多个observer采取不同Action
*/
// 观察者(基类)
class observer{
public:
observer(){}
virtual ~observer(){}
virtual void update(double);
protected:
double observer_state;
};
// 观察者1(具体)
class concreteObserver_1:public observer
{
void update(double newstate)
{
// 同步状态
observer_state = newstate;
// do something
}
};
// 观察者2(具体)
class concreteObserver_2:public observer
{
void update(double newstate)
{
// 同步状态
observer_state = newstate;
// do something
}
};
// 抽象目标
class subject{
public:
void attach(observer* one){
observers_.push_back(one);
}
void detach(observer* one){
observers_.remove(one);
}
// 通知观察者状态已经改变,让其采取某种行为
void notifyObserver(double num_state)
{
for(auto& observer: observers_)
{
observer->update(num_state);
}
}
void set_num_state(double new_state)
{
subject_state_ = new_state;
notifyObserver(subject_state_);
}
private:
// 观察者列表
std::list<observer* > observers_;
// 状态
double subject_state_;
};