Simple Observer Pattern

Send Snippet To: Save this snippet to Code Collector Pro -- view all watchman's snippets
language: C
license: Other

Code for Snippet:

// Note that this code only works with the c++11 standard
// From: (15th April 2014)
/* ========= Subject class ========= */
#include <functional>  // for std::function
#include <utility>     // for std::forward and std::move
#include <map>
#include <vector>
template <typename Event>
class Subject
  template <typename Observer>
  void registerObserver(const Event& event, Observer&& observer)
  template <typename Observer>
  void registerObserver(Event&& event, Observer&& observer)
  void notify(const Event& event) const
    for (const auto& obs : obs();
  std::map<Event, std::vector<std::function<void()>>> observers_;
/* ========= Simple Usage ========= */
int main()
  Subject<std::string> s;
  s.registerObserver("GREEN", bar);
  s.registerObserver("ORANGE", std::bind(foo, 42));
  s.registerObserver("RED", std::bind(foo, 12345));
  const std::string msg("Hello, RED!");
  s.registerObserver("RED", [&msg]{std::cout << msg << std::endl;});
comments powered by Disqus


Link to this snippet:

Download to Code Collector

To use the direct link to your snippet on either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 775
Date Added: 2014-04-15 13:50:28
Last Modified: 2014-04-15 07:50:42

Web Analytics