私はこのように動作するはずのオブザーバー パターンを設計しています: オブザーバーはAddEventListenerメソッドを呼び出し、EventDispatcherの名前である文字列を渡します。event
その後、 ;eventの内部で発生します。EventDispatcherサブスクリプションのリストを調べて、サブスクリプションがある場合は、このイベントに割り当てられた のactionメソッドを呼び出しますobserver。
ここまで来ましたEventDispatcher.h。注意には、疑似コードが含まれています。
次の 2 つの質問があります。
actioninの型を定義するにはどうすればよい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 );
};
};
};