我設計應該以這種方式工作的觀察者模式:觀察者稱的EventDispatcher
AddEventListener
方法,並傳遞一個字符串,它是event
的名稱,PointerToItself和PointerToItsMemberMethodC++自己的Observer模式
之後event
發生在EventDispatcher
內部;它查看訂閱列表,如果有一些,分配給此事件調用observer
的action
方法。
我來到這EventDispatcher.h
。 小心包含一些僞代碼。
的是兩個問題:
- 如何定義的
action
在struct Subscription
類型? - 我是否正確地移動?
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);
};
};
};
壞你」不要使用增強功能,因爲這樣可以實現一種簡單且類型安全的解決方案,該解決方案將超越您當前的方法並且更加靈活。 C++ 11解決方案是否允許? – Ylisar
我還不知道,C++ 11是什麼......這是一個新標準,對吧?我想知道,如果我的'g ++'知道它已經?新標準可以使用,它不是一個庫... – Kolyunya