-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver_2.hpp
66 lines (56 loc) · 1.3 KB
/
observer_2.hpp
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
#ifndef OBSERVER_2_HPP_INCLUDED
#define OBSERVER_2_HPP_INCLUDED 1
#include <algorithm>
#include <cassert>
#include <list>
template <typename T> class Subject;
template <typename T>
class Observer
{
public:
virtual ~Observer() {}
virtual void update(Subject<T> *subject) = 0;
};
template <typename T>
class Subject
{
public:
typedef Observer<T> observer_type;
typedef std::list<observer_type *> observer_list_type;
virtual ~Subject() { notify(); }
void attach(observer_type *o);
void detach(observer_type *o);
void notify();
private:
observer_list_type observers_;
void detach_observer(observer_type *o);
};
template <typename T>
inline void Subject<T>::attach(observer_type *o)
{
assert(o != NULL);
typename observer_list_type::iterator i = std::find(observers_.begin(), observers_.end(), o);
if (i == observers_.end()) {
observers_.push_back(o);
}
}
template <typename T>
inline void Subject<T>::detach(observer_type *o)
{
assert(o != NULL);
detach_observer(o);
}
template <typename T>
inline void Subject<T>::notify()
{
observer_list_type l(observers_.begin(), observers_.end());
for (auto o: l) {
o->update(this);
}
}
template <typename T>
inline void Subject<T>::detach_observer(observer_type *o)
{
observers_.remove(o);
}
#endif // !defined(OBSERVER_2_HPP_INCLUDED)