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: http://juanchopanzacpp.wordpress.com/2013/02/24/simple-observer-pattern-implementation-c11/ (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
{
 public:
 
  template <typename Observer>
  void registerObserver(const Event& event, Observer&& observer)
  {
    observers_[event].push_back(std::forward<Observer>(observer));
  }
 
  template <typename Observer>
  void registerObserver(Event&& event, Observer&& observer)
  {
    observers_[std::move(event)].push_back(std::forward<Observer>(observer));
  }
 
  void notify(const Event& event) const
  {
    for (const auto& obs : observers_.at(event)) obs();
  }
 
 private:
  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;});
 
  s.notify("GREEN");
  s.notify("RED");
  s.notify("ORANGE");
}
comments powered by Disqus

Info

Link to this snippet:


Download to Code Collector

To use the direct link to your snippet on CodeCollector.net 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: 753
Date Added: 2014-04-15 13:50:28
Last Modified: 2014-04-15 07:50:42

Web Analytics