【发布时间】:2012-08-19 18:35:05
【问题描述】:
我正在设计一个应该以这种方式工作的观察者模式:观察者调用EventDispatcher 的AddEventListener 方法并传递一个字符串,该字符串是event 的名称、PointerToItself 和PointerToItsMemberMethod
之后event 发生在EventDispatcher 内部;它会查看订阅列表,如果有的话,分配给这个事件的会调用observer 的action 方法。
我来到了这个EventDispatcher.h。 注意包含一些伪代码。
有两个问题:
- 如何在
struct Subscription中定义action的类型? - 我走对了吗?
PS:不,我不会使用boost 或任何其他库。
#pragma once
#include <vector>
#include <string>
using namespace std;
struct Subscription
{
void* observer;
string event;
/* u_u */ action;
};
class EventDispatcher
{
private:
vector<Subscription> subscriptions;
protected:
void DispatchEvent ( string event );
public:
void AddEventListener ( Observer* observer , string event , /* u_u */ action );
void RemoveEventListener ( Observer* observer , string event , /* u_u */ action );
};
这个头在EventDispatcher.cpp中是这样实现的
#include "EventDispatcher.h"
void EventDispatcher::DispatchEvent ( string event )
{
int key = 0;
while ( key < this->subscriptions.size() )
{
Subscription subscription = this->subscriptions[key];
if ( subscription.event == event )
{
subscription.observer->subscription.action;
};
};
};
void EventDispatcher::AddEventListener ( Observer* observer , string event , /* */ action )
{
Subscription subscription = { observer , event , action );
this->subscriptions.push_back ( subscription );
};
void EventDispatcher::RemoveEventListener ( Observer* observer , string event , /* */ action )
{
int key = 0;
while ( key < this->subscriptions.size() )
{
Subscription subscription = this->subscriptions[key];
if ( subscription.observer == observer && subscription.event == event && subscription.action == action )
{
this->subscriptions.erase ( this->subscriptions.begin() + key );
};
};
};
【问题讨论】:
-
不幸的是,您没有使用 boost,因为这将允许一个简单且类型安全的解决方案,该解决方案将优于您当前的方法并且更加灵活。是否允许使用 C++11 解决方案?
-
我还不知道,C++11 是什么……这是一个新标准,对吧?我想知道,如果我的
g++已经知道了吗?新标准可以用,不是库……
标签: c++ pointers function-pointers observer-pattern observers