学向勤中得,萤窗万卷书。这篇文章主要讲述观察者模式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;
}
推荐阅读
- #yyds干货盘点# go template模板语法
- #yyds干货盘点#分析一个错误使用MemoryCache导致的BUG
- #yyds干货盘点#登天之梯——Pandas快速入门(下)
- #yyds干货盘点#借助AI模型目标检测打标签工具 (Makesense.ai , 解放双手 ! ! !)
- Alibaba中间件技术「RocketMQ专题」探索DefaultMQPushConsumer
- 第五章-Java修饰符#yyds干货盘点#
- 「Oracle」Oracle 数据库安装
- 有关synchronized锁的知识点,我用一篇文章总结了
- Go 语言入门很简单 -- 7. Go Slices #私藏项目实操分享#