-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.h
57 lines (45 loc) · 852 Bytes
/
observer.h
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
#ifndef OBSERVER_H
#define OBSERVER_H
template<typename ...Args>
class Subject;
struct AbstractObserver
{
};
using ObserverPointer = std::shared_ptr<AbstractObserver>;
template<typename ...Args>
struct Observer : public AbstractObserver
{
using SubjectType = Subject<Args...>;
using Function = std::function<void(Args ...)>;
SubjectType *s = nullptr;
Function f;
Observer(SubjectType *subject, Function func) :
s(subject), f(func)
{
attach();
}
~Observer()
{
detach();
}
void attach()
{
if (s)
s->attach(this);
}
void detach()
{
if (s)
s->detach(this);
s = nullptr;
}
void reset()
{
s = nullptr;
}
void notify(Args ...args)
{
f(args...);
}
};
#endif // OBSERVER_H