Created
August 18, 2013 16:12
-
-
Save vannell/6262436 to your computer and use it in GitHub Desktop.
C++ dummy Observer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef LISTENABLE_H | |
#define LISTENABLE_H | |
class Listener { | |
}; | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "Observable.h" | |
#include "Listener.h" | |
using namespace std; | |
class A : public Listener { | |
public: | |
void print(double val) { | |
cout << "A::print "<< val << endl; | |
} | |
void dbl(double val) { | |
cout << "A::dbl " << val * 2 << endl; | |
} | |
}; | |
int main() { | |
Observable obs; | |
A a; | |
obs.registerListener(&a, (void (Listener::*) (double)) &A::print); | |
obs.registerListener(&a, (void (Listener::*) (double)) &A::dbl); | |
obs.setValue(42.0); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Observable.h" | |
using namespace std; | |
void Observable::registerListener(Listener* listener, void (Listener::*callback) (double)) { | |
m_listeners.insert(pair<Listener*, void (Listener::*) (double)>(listener, callback)); | |
} | |
void Observable::setValue(double value) { | |
/* do whatever you want with value*/ | |
update(value); | |
} | |
void Observable::update(double value) { | |
multimap< Listener*, void (Listener::*) (double) >::iterator it = m_listeners.begin(); | |
while (it != m_listeners.end()) { | |
Listener* l = it->first; | |
void (Listener::*meth) (double) = it->second; | |
(l->*meth)(value); | |
it++; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef OBSERVABLE_H | |
#define OBSERVABLE_H | |
#include <map> | |
#include "Listener.h" | |
class Observable { | |
public: | |
void registerListener(Listener* listener, void (Listener::*callback) (double)); | |
void setValue(double value); | |
protected: | |
std::multimap< Listener*, void (Listener::*) (double)> m_listeners; | |
void update(double value); | |
}; | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment