Libftpp
A modern C++ library
observer.hpp
Go to the documentation of this file.
1 #ifndef OBSERVER_HPP
2 #define OBSERVER_HPP
3 
4 #include <functional>
5 #include <stdexcept>
6 #include <string>
7 #include <unordered_map>
8 #include <vector>
24 template <typename TEvent>
25 class Observer
26 {
27 private:
28  std::unordered_map<TEvent, std::vector<std::function<void()>>> _events;
29 
30 public:
31  void subscribe(const TEvent& event, const std::function<void()>& lambda)
32  {
33  _events[event].push_back(lambda);
34  }
35 
36  void notify(const TEvent& event)
37  {
38  // We can also use auto to simplify the code
39  // auto it = _events.find(event);
40 
41  // Note: On doit typename les iterators dans les templates
42  typename std::unordered_map<TEvent, std::vector<std::function<void()>>>::iterator it =
43  _events.find(event);
44 
45  if (it == _events.end())
46  return;
47 
48  for (const auto& funct : it->second)
49  funct();
50  }
51 };
52 #endif
Observer Design Pattern.
Definition: observer.hpp:26
void subscribe(const TEvent &event, const std::function< void()> &lambda)
Definition: observer.hpp:31
void notify(const TEvent &event)
Definition: observer.hpp:36