LIBTHEMIS
listen.h
[詳解]
1 /*************************************************************************//*
11  * (c) 2001-2018 oZ/acy. ALL RIGHTS RESERVED.
12  */
13 #ifndef INC_THEMIS_LISTENER_H___
14 #define INC_THEMIS_LISTENER_H___
15 
16 #include <list>
17 #include <algorithm>
18 #include <boost/utility.hpp>
19 
20 namespace themis
21 {
22  template<class E_> class Listener;
23  template<class E_> class Talker;
24 }
25 
26 
30 template<class E_>
31 class themis::Listener : boost::noncopyable
32 {
33  friend class themis::Talker<E_>;
34 
35 private:
36  themis::Talker<E_>* tkr_;
37 
38 public:
40  constexpr Listener() noexcept : tkr_(nullptr) {}
41 
43  virtual ~Listener()
44  {
45  if (tkr_)
46  tkr_->remove(this);
47  }
48 
53  virtual void update(const E_&) =0;
54 
55 private:
61  void setTalker__(themis::Talker<E_>* t)
62  {
63  if (tkr_)
64  tkr_->remove(this);
65  tkr_ = t;
66  }
67 
73  void removeFromTalker__()
74  {
75  tkr_ = nullptr;
76  }
77 };
78 
79 
83 template<class E_>
84 class themis::Talker : boost::noncopyable
85 {
86 private:
87  std::list<themis::Listener<E_>*> lsns_;
88 
89 public:
91  constexpr Talker() noexcept {}
92 
94  virtual ~Talker()
95  {
96  for (auto it = lsns_.begin(); it != lsns_.end(); it++)
97  (*it)->removeFromTalker__();
98  }
99 
100 
105  {
106  auto it = std::find(lsns_.begin(), lsns_.end(), lsn);
107  if (it == lsns_.end()) {
108  lsns_.push_back(lsn);
109  lsn->addToTalker__(this);
110  }
111  }
112 
113 
117  void remove(themis::Listener<E_>* lsn)
118  {
119  auto it = std::find(lsns_.begin(), lsns_.end(), lsn);
120  if (it != lsns_.end())
121  {
122  (*it)->removeFromTalker__();
123  lsns_.erase(it);
124  }
125  }
126 
132  void notify(const E_& e)
133  {
134  for (auto it = lsns_.begin(); it != lsns_.end(); it++)
135  (*it)->update(e);
136  }
137 };
138 
139 
140 
141 
142 #endif // INC_THEMIS_LISTENER_H___
constexpr Talker() noexcept
デフォルト構築子
Definition: listen.h:91
Definition: except.h:17
イベントE_をTalker<E_>から通知されて處理するクラスの基底
Definition: listen.h:22
void notify(const E_ &e)
イベント通知
Definition: listen.h:132
イベント E_ を Listener<E_> に一齊通知するクラスの基底
Definition: listen.h:23
virtual ~Talker()
解體子
Definition: listen.h:94
virtual ~Listener()
解體子
Definition: listen.h:43
void add(themis::Listener< E_ > *lsn)
リスナーlsnをイベント通知對象に追加
Definition: listen.h:104
void remove(themis::Listener< E_ > *lsn)
リスナーlsnをイベント通知對象から除去
Definition: listen.h:117
constexpr Listener() noexcept
デフォルト構築子
Definition: listen.h:40
virtual void update(const E_ &)=0
更新(イベント通知)