I create an observer pattern that should work this way: observer calls the AddEventListener EventDispatcher method and passes a string that is named event , PointerToItself and PointerToItsMemberMethod
After that, the event occurs inside the EventDispatcher ; he looks at the list of subscriptions, and if there are some assigned to this event, he calls the action observer method.
I came to this EventDispatcher.h . CAUTION contains a pseudo-code bit.
These are two questions:
- How to determine type of
action in struct Subscription ? - Am I moving right?
PS : No, I will not 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 is implemented as follows: 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 ); }; }; };
source share