观察者模式C++实现

学向勤中得,萤窗万卷书。这篇文章主要讲述观察者模式C++实现相关的知识,希望能为你提供帮助。
【观察者模式C++实现】观察者模式

Exe : Observer.o g++ -o Exe Observer.o main.o : Observer.cpp g++ -g -c Observer.cpp clean : rm Observer

#include < iostream> #include < string> #include < list> using namespace std; class Observer { public: bool bool_state = false; void change_state(); }; void Observer::change_state() { cout < < "before change Observer state : " < < bool_state < < endl; bool_state = bool_state ? false : true; cout < < "after change Observer state : " < < bool_state < < endl; }class Object { public: list< Observer*> Observer_list; bool bool_state = false; void add_list(Observer* ptr); void delete_list(Observer* ptr); void notice(); void change_state(); }; void Object::add_list(Observer* ptr) { Observer_list.push_back(ptr); }void Object::delete_list(Observer* ptr) { Observer_list.remove(ptr); }void Object::notice() { for(list< Observer*> ::iterator iter = Observer_list.begin(); iter != Observer_list.end(); iter++) { (*iter)-> change_state(); } } void Object::change_state() { cout < < "before change Object state : " < < bool_state < < endl; bool_state = bool_state ? false : true; cout < < "after change Object state : " < < bool_state < < endl; notice(); }int main(void) { Observer* p_Observer = new Observer; Observer* p_Observer_2 = new Observer; Object* p_Object = new Object; p_Object-> add_list(p_Observer); p_Object-> add_list(p_Observer_2); p_Object-> change_state(); delete p_Object; delete p_Observer; delete p_Observer_2; return 0; }


    推荐阅读