I'm designing an observer pattern which should work this way: observer calls AddEventListener
method of EventDispatcher
and passes a string which is the name of the event
, PointerToItself and a PointerToItsMemberMethod
After that event
happens inside of the EventDispatcher
; it looks through the list of subscriptions and if there are some, assigned to this event calls the action
method of the observer
.
I've come to this EventDispatcher.h
. CAUTION contains bit of pseudo-code.
The are two questions:
- How do I define the type of
action
instruct Subscription
? - Am I moving the right way?
PS: No, I'm not gonna use boost
or any other libraries .
#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 );
};
This header implements like this in 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 );
};
};
};