-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathobserver.cpp
More file actions
103 lines (90 loc) · 2.24 KB
/
observer.cpp
File metadata and controls
103 lines (90 loc) · 2.24 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*!
* Example largely inspired by
* http://www.vishalchovatiya.com/observer-design-pattern-in-modern-cpp
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
/*!
* @brief Observer
* Defines an updating interface for objects that
* should be notified of changes in a Subject.
*/
template <typename T>
class Observer
{
public :
virtual ~Observer() = default;
virtual void update(T &p_src, const std::string &p_field) = 0;
protected:
Observer() = default;
};
/*!
* @brief Subject
* Defines an interface for adding/removing subcribers
* Keeps track of its Observers.
*/
template <typename T>
class Subject
{
public:
virtual ~Subject() = default;
void notify(T &p_src, const std::string &p_field)
{
for ( auto l_obs : m_observers )
l_obs->update(p_src, p_field);
}
void subscribe (Observer<T>* p_obs) { m_observers.push_back(p_obs); }
void unsubscribe(Observer<T>* p_obs)
{
m_observers.erase(std::remove(std::begin(m_observers),
std::end (m_observers),
p_obs),
std::end(m_observers) );
}
protected:
Subject() = default;
private:
std::vector<Observer<T>* > m_observers;
};
struct Person : Subject<Person>
{
void set_age(uint8_t age)
{
auto old_can_vote = get_can_vote();
this->m_age = age;
notify(*this, "age");
if (old_can_vote != get_can_vote())
notify(*this, "can_vote");
}
uint8_t get_age() const { return m_age; }
bool get_can_vote() const { return m_age >= 16; }
private:
uint8_t m_age{0};
};
struct TrafficAdministration : Observer<Person>
{
void update(Person &p_src, const std::string &p_field)
{
if ( p_field == "age" )
{
if ( p_src.get_age() < 17 )
std::cout << "Not old enough to drive!\n";
else
{
std::cout << "Mature enough to drive!\n";
p_src.unsubscribe(this);
}
}
}
};
int main()
{
Person p;
TrafficAdministration ta;
p.subscribe(&ta);
p.set_age(16);
p.set_age(17);
return EXIT_SUCCESS;
}