观察者模式
场景:
多个观察者观察一个目标对象的状态,若该目标对象状态发生改变,则观察者会对此作出反应
实现:
目标对象:
1.状态变量
2.观察者列表
3.attach成员函数用于向观察者列表中添加观察者
4.detach成员函数,用于删除观察者列表中的观察者成员
5.notify函数,用于当状态变量发生变化时,通知观察者
观察者:
1.观察者应该有多个,所以最好应该有一个抽象类
2.update成员函数,用于当目标对象状态变量发生改变时,观察者作出反应
优点:
任何时候,只要状态变量发生改变,观察者立刻就能发生改变
//代码 //object.h #pragma once #include <list> #include "IObserver.h" class object { public: object(); ~object(); void attach(IObserver* observer); void detach(IObserver* observer); void notify(); void set_state(int state); private: std::list<IObserver*> m_list; int m_state; }; //object.cpp #include "pch.h" #include "object.h" object::object():m_state(0) { } object::~object() { } void object::set_state(int state) { m_state = state; } void object::attach(IObserver* observer) { m_list.push_back(observer); } void object::detach(IObserver* observer) { m_list.remove(observer); } void object::notify() { std::list<IObserver*>::iterator it = m_list.begin(); for (;it!=m_list.end();it++) { (*it)->update(m_state); } } //IObserver.h #pragma once #include <iostream> class IObserver { public: IObserver(); ~IObserver(); virtual void update(int state) = 0; }; class ObserverA :public IObserver { void update(int state); }; class ObserverB :public IObserver { void update(int state); }; //IOberser.vpp #include "pch.h" #include "IObserver.h" IObserver::IObserver() { } IObserver::~IObserver() { } void ObserverA::update(int state) { std::cout << "ObserverA:" << state << std::endl; } void ObserverB::update(int state) { std::cout << "ObserverB:" << state << std::endl; } //测试代码 #include "pch.h" #include <iostream> #include "IObserver.h" #include "object.h" #ifndef SAFE_DELETE_POINTER #define SAFE_DELETE_POINTER(p){if(p) delete(p); (p)=NULL;} #endif int main() { object* v_object = new object; IObserver* observera = new ObserverA; IObserver* observerb = new ObserverB; v_object->set_state(23); v_object->attach(observera); v_object->attach(observerb); v_object->notify(); v_object->detach(observera); v_object->detach(observerb); SAFE_DELETE_POINTER(v_object); SAFE_DELETE_POINTER(observera); SAFE_DELETE_POINTER(observerb); getchar(); }
运行结果:
ObserverA:23
ObserverB:23