观察者模式C++实现
Posted 潇湘二胡
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了观察者模式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;
}
以上是关于观察者模式C++实现的主要内容,如果未能解决你的问题,请参考以下文章