Caffe2 - C++ API
A deep learning, cross platform ML framework
observer.h
1 
17 #pragma once
18 
19 #include <memory>
20 #include <unordered_set>
21 #include "caffe2/core/logging.h"
22 
23 namespace caffe2 {
24 
29 template <class T>
30 class ObserverBase {
31  public:
32  explicit ObserverBase(T* subject) : subject_(subject) {}
33 
34  virtual void Start() {}
35  virtual void Stop() {}
36 
37  virtual std::unique_ptr<ObserverBase<T>> copy(T* subject) {
38  LOG(WARNING) << "copy() is not implemented and nullptr will be returned.";
39  return nullptr;
40  }
41 
42  virtual std::string debugInfo() {
43  return "Not implemented.";
44  }
45 
46  virtual ~ObserverBase() noexcept {};
47 
48  T* subject() const {
49  return subject_;
50  }
51 
52  protected:
53  T* subject_;
54 };
55 
59 template <class T>
60 class Observable {
61  public:
62  virtual ~Observable(){};
63  using Observer = ObserverBase<T>;
64 
65  /* Returns a reference to the observer after addition. */
66  const Observer* AttachObserver(std::unique_ptr<Observer> observer) {
67  CAFFE_ENFORCE(observer, "Couldn't attach a null observer.");
68  std::unordered_set<const Observer*> observers;
69  for (auto& ob : observers_list_) {
70  observers.insert(ob.get());
71  }
72 
73  const auto* observer_ptr = observer.get();
74  if (observers.count(observer_ptr)) {
75  return observer_ptr;
76  }
77  observers_list_.push_back(std::move(observer));
78 
79  return observer_ptr;
80  }
81 
86  std::unique_ptr<Observer> DetachObserver(const Observer* observer_ptr) {
87  for (auto it = observers_list_.begin(); it != observers_list_.end(); ++it) {
88  if (it->get() == observer_ptr) {
89  auto res = std::move(*it);
90  observers_list_.erase(it);
91  return res;
92  }
93  }
94  return nullptr;
95  }
96 
97  virtual size_t NumObservers() {
98  return observers_list_.size();
99  }
100 
101  void StartAllObservers() {
102  for (auto& observer : observers_list_) {
103  observer->Start();
104  }
105  }
106 
107  void StopAllObservers() {
108  for (auto& observer : observers_list_) {
109  observer->Stop();
110  }
111  }
112 
113  protected:
114  std::vector<std::unique_ptr<Observer>> observers_list_;
115 };
116 
117 } // namespace caffe2
Use this to implement a Observer using the Observer Pattern template.
Definition: observer.h:30
std::unique_ptr< Observer > DetachObserver(const Observer *observer_ptr)
Returns a unique_ptr to the removed observer.
Definition: observer.h:86
Inherit to make your class observable.
Definition: observer.h:60
Copyright (c) 2016-present, Facebook, Inc.