-
Notifications
You must be signed in to change notification settings - Fork 2
/
observer.hpp
68 lines (57 loc) · 1.56 KB
/
observer.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
67
68
#ifndef OBSERVER_HPP
#define OBSERVER_HPP
#include <iostream>
#include <list>
#include <memory>
#include <mutex>
class Observer : public std::enable_shared_from_this<Observer>
{
public:
virtual ~Observer() {}
virtual void update(int) = 0;
};
class Subject
{
public:
virtual ~Subject() {}
virtual void attach(std::weak_ptr<Observer>) = 0;
virtual void detach(std::weak_ptr<Observer>) = 0;
virtual void notify() = 0;
};
class PhoneObserver : public Observer
{
public:
virtual void update(int i) { std::cout << "This is PhoneObserver " << i << std::endl; }
};
class ComputerObserver : public Observer
{
public:
virtual void update(int i) { std::cout << "This is ComputerObserver " << i << std::endl; }
};
class ConcreteSubject : public Subject
{
public:
virtual void attach(std::weak_ptr<Observer> observerPtr) { m_Observers.push_back(observerPtr); }
virtual void detach(std::weak_ptr<Observer> observerPtr)
{
m_Observers.remove_if(
[=](const std::weak_ptr<Observer> &ptr1) { return observerPtr.lock() == ptr1.lock(); });
}
virtual void notify()
{
for (auto iter = m_Observers.begin(); iter != m_Observers.end();) {
auto share = (*iter).lock();
if (share) {
share->update(m_state);
iter++;
} else {
iter = m_Observers.erase(iter);
}
}
}
void setState(int state) { m_state = state; }
private:
std::list<std::weak_ptr<Observer>> m_Observers;
int m_state = 0;
};
#endif // OBSERVER_HPP