summaryrefslogtreecommitdiff
path: root/core/fxcrt/include/cfx_observable.h
diff options
context:
space:
mode:
authortsepez <tsepez@chromium.org>2016-09-07 14:11:27 -0700
committerCommit bot <commit-bot@chromium.org>2016-09-07 14:11:27 -0700
commit7b68f616e49235267eeac8db51aadade6d60e243 (patch)
treee49619edf4ff8f7b10adec869bb30dcc4a1b88f9 /core/fxcrt/include/cfx_observable.h
parentf56d93f8ea1c2145401e99e61cefdbfcb7341229 (diff)
downloadpdfium-7b68f616e49235267eeac8db51aadade6d60e243.tar.xz
Make Observers into a templated class
Review-Url: https://codereview.chromium.org/2311343003
Diffstat (limited to 'core/fxcrt/include/cfx_observable.h')
-rw-r--r--core/fxcrt/include/cfx_observable.h66
1 files changed, 66 insertions, 0 deletions
diff --git a/core/fxcrt/include/cfx_observable.h b/core/fxcrt/include/cfx_observable.h
new file mode 100644
index 0000000000..b669e0d3d5
--- /dev/null
+++ b/core/fxcrt/include/cfx_observable.h
@@ -0,0 +1,66 @@
+// Copyright 2016 PDFium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CORE_FXCRT_INCLUDE_CFX_OBSERVABLE_H_
+#define CORE_FXCRT_INCLUDE_CFX_OBSERVABLE_H_
+
+#include <set>
+
+#include "core/fxcrt/include/fx_system.h"
+#include "third_party/base/stl_util.h"
+
+template <class T>
+class CFX_Observable {
+ public:
+ class Observer {
+ public:
+ Observer() : m_pWatchedPtr(nullptr) {}
+ Observer(T** pWatchedPtr) : m_pWatchedPtr(pWatchedPtr) {
+ if (m_pWatchedPtr)
+ (*m_pWatchedPtr)->AddObserver(this);
+ }
+ Observer(const Observer& that) = delete;
+ ~Observer() {
+ if (m_pWatchedPtr)
+ (*m_pWatchedPtr)->RemoveObserver(this);
+ }
+ void SetWatchedPtr(T** pWatchedPtr) {
+ if (m_pWatchedPtr)
+ (*m_pWatchedPtr)->RemoveObserver(this);
+ m_pWatchedPtr = pWatchedPtr;
+ if (m_pWatchedPtr)
+ (*m_pWatchedPtr)->AddObserver(this);
+ }
+ void OnDestroy() {
+ ASSERT(m_pWatchedPtr);
+ *m_pWatchedPtr = nullptr;
+ m_pWatchedPtr = nullptr;
+ }
+ Observer& operator=(const Observer& that) = delete;
+
+ private:
+ T** m_pWatchedPtr;
+ };
+
+ CFX_Observable() {}
+ CFX_Observable(const CFX_Observable& that) = delete;
+ ~CFX_Observable() {
+ for (auto* pObserver : m_Observers)
+ pObserver->OnDestroy();
+ }
+ void AddObserver(Observer* pObserver) {
+ ASSERT(!pdfium::ContainsKey(m_Observers, pObserver));
+ m_Observers.insert(pObserver);
+ }
+ void RemoveObserver(Observer* pObserver) {
+ ASSERT(pdfium::ContainsKey(m_Observers, pObserver));
+ m_Observers.erase(pObserver);
+ }
+ CFX_Observable& operator=(const CFX_Observable& that) = delete;
+
+ private:
+ std::set<Observer*> m_Observers;
+};
+
+#endif // CORE_FXCRT_INCLUDE_CFX_OBSERVABLE_H_