summaryrefslogtreecommitdiff
path: root/core/fxcrt/include/cfx_observable.h
blob: 99a995128492f2f52f29db73196b7bcf8cb73fa0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 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() { NotifyObservers(); }
  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);
  }
  void NotifyObservers() {
    for (auto* pObserver : m_Observers)
      pObserver->OnDestroy();
    m_Observers.clear();
  }
  CFX_Observable& operator=(const CFX_Observable& that) = delete;

 private:
  std::set<Observer*> m_Observers;
};

#endif  // CORE_FXCRT_INCLUDE_CFX_OBSERVABLE_H_