实施观察者模式C
Implementing Observer pattern C++
本文关键字:观察者模式 更新时间:2023-10-16
我正在研究Android中的C 项目。我要实现的是在C 中进行异步调用,然后通过JNI将数据发送回数据。这是一个简单的概念证明,但这也意味着我的C 已知gone是有限的。
我已经有所有功能工作,但是想让项目的C 侧"更好",我想实现观察者模式。我以此为教程:http://www.codeproject.com/articles/328365/understanding-and-implementing-observer-pattern-in
添加所有内容(已修改为项目)后,我会收到以下编译错误:模板参数2在行中的asubject.h中无效:
std::vector<PoCCplusplus*> list;
主题h和cpp:
#pragma once
#include <vector>
#include <list>
#include <algorithm>
#include "PoCCplusplus.h"
class ASubject
{
//Lets keep a track of all the shops we have observing
std::vector<PoCCplusplus*> list;
public:
void Attach(PoCCplusplus *cws);
void Detach(PoCCplusplus *cws);
void Notify(char *xml);
};
#include "ASubject.h"
using namespace std;
void ASubject::Attach(PoCCplusplus *cws)
{
list.push_back(cws);
}
void ASubject::Detach(PoCCplusplus *cws)
{
list.erase(std::remove(list.begin(), list.end(), cws), list.end());
}
void ASubject::Notify(char *xml)
{
for(vector<PoCCplusplus*>::const_iterator iter = list.begin(); iter != list.end(); ++iter)
{
if(*iter != 0)
{
(*iter)->Update(xml);
}
}
}
这可能是我缺少的非常简单的事情,但我只是找不到解决方案。
- 将
list
属性重命名为ASubject
中的其他内容,例如observedShops
(如您的评论中所述)。 - 在库代码中避免使用
using namespace std
。
you
#include <list>
so'list'已经是一种定义的类型。选择一个不同的变量名称。
这就是为什么不使用的好主意:
using namespace std;
另外,如果您使用boost :: Signals2:
#include <boost/signals2.hpp>
#include <boost/bind.hpp>
using namespace std;
using boost::signals2::signal;
using boost::bind;
struct Some {
void Update(char* xml) {
cout << "Updaten";
}
void operator()(char* xml) {
cout << "operatorn";
}
};
void func(char* xml) {
cout << "funcn";
}
int main() {
signal<void(char*)> s;
Some some;
Some other;
s.connect(some);
s.connect(bind(&Some::Update, other, _1));
s.connect(func);
char str[10] = "some str";
s(str);
return 0;
}
相关文章:
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 反射 + 函数指针与观察者模式
- 观察者模式不起作用
- 观察者模式:为什么主题应该是抽象的?
- 观察者模式专业化
- 如何在不必绑定到特定类的情况下实现观察者模式
- C++,函数指针与观察者模式
- C++11观察者模式(信号、插槽、事件、更改广播器/侦听器,或任何您想称之为的东西)
- 实施观察者模式C
- C++自己的观察者模式
- 不同可观察量的观察者模式
- 通过Boost信号的观察者模式2
- 具有类型信息的观察者模式(C++)
- 代码设计:观察者模式
- 观察者模式和继承:未调用正确的函数
- C++和Qt:观察者模式错误
- 在C++中实现观察者模式
- 多少听众是太多的观察者模式
- 当观察者希望观察不同的项目时实现观察者模式
- 通用观察者模式