Created
September 17, 2018 13:13
-
-
Save denyszamiatin/d5052eb6de3be2a7ccc97ad2d4b6d884 to your computer and use it in GitHub Desktop.
Observer example
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 <vector> | |
#include <map> | |
#include <functional> | |
using namespace std; | |
using observer = function<void()>; | |
enum class Events {A, B, C}; | |
template<typename Event> | |
class Observer { | |
public: | |
void registerObs(Event e, observer obs) { | |
observers[e].push_back(obs); | |
}; | |
void notify(Event e) { | |
for(auto obs: observers.at(e)) { | |
obs(); | |
} | |
}; | |
private: | |
map<Event, vector<observer>> observers; | |
}; | |
int main() { | |
Observer<Events> o; | |
o.registerObs(Events::A, bind([](string s){ cout << s << endl; }, "A1")); | |
o.registerObs(Events::A, bind([](string s){ cout << s << endl; }, "A2")); | |
o.registerObs(Events::B, bind([](string s){ cout << s << endl; }, "B1")); | |
o.notify(Events::A); | |
o.notify(Events::B); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment