实施观察者模式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;
}