Skip to content

Instantly share code, notes, and snippets.

@mortennobel
Last active December 16, 2015 03:39
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 mortennobel/5371812 to your computer and use it in GitHub Desktop.
Save mortennobel/5371812 to your computer and use it in GitHub Desktop.
Observer pattern in C++11
//
// main.cpp
// Observer pattern in C++11
//
// Created by Morten Nobel-Jørgensen on 9/21/12.
// Copyright (c) 2012 Morten Nobel-Joergensen. All rights reserved.
//
#include <iostream>
using namespace std;
using namespace std::placeholders;
#include <iostream>
#include <functional>
#include <vector>
class Foo {
public:
void addValueListener(std::function<void (Foo*)> listener){
valueListeners.push_back(listener);
}
void removeValueListener(std::function<void (Foo*)> listener){
// ....
}
void setValue(int value){
if (value != this->value){
this->value = value;
fireValueUpdated();
}
}
int getValue(){
return value;
}
private:
void fireValueUpdated(){
for (auto &f:valueListeners) {
f(this);
}
}
int value;
std::vector<std::function<void (Foo*)>> valueListeners;
};
class Moo {
public:
Moo(std::string s):s(s) {}
void FooUpdated(Foo *f){
std::cout << s<< " saw foo value updated to " << f->getValue() << std::endl;
}
private:
std::string s;
};
int main(int argc, const char * argv[])
{
Foo f;
f.setValue(123);
f.addValueListener([] (Foo *f){
cout << "New Foo value "<<f->getValue()<<endl;
});
f.setValue(124);
Moo m("Moo#1");
f.addValueListener([&m](Foo *f){m.FooUpdated(f);});
f.setValue(125);
Moo m2("Moo#2");
f.addValueListener(bind(&Moo::FooUpdated,m2, _1));
f.setValue(126);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment