Skip to content

Instantly share code, notes, and snippets.

@denyszamiatin
Created September 17, 2018 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denyszamiatin/d5052eb6de3be2a7ccc97ad2d4b6d884 to your computer and use it in GitHub Desktop.
Save denyszamiatin/d5052eb6de3be2a7ccc97ad2d4b6d884 to your computer and use it in GitHub Desktop.
Observer example
#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