-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathConceptualExample01.cpp
More file actions
208 lines (161 loc) · 5.91 KB
/
Copy pathConceptualExample01.cpp
File metadata and controls
208 lines (161 loc) · 5.91 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// ===========================================================================
// ConceptualExample01.cpp // Observer // Variant 1
// ===========================================================================
/**
* Observer Design Pattern
*/
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif // _DEBUG
#include <map>
#include <memory>
#include <print>
#include <string>
#include <string_view>
#include <vector>
namespace ConceptualExample_Observer_Pattern {
class IObserver {
public:
virtual ~IObserver() = default;
virtual void update(std::string_view message) = 0;
};
class ISubject {
public:
virtual ~ISubject() = default;
virtual void attach(std::weak_ptr<IObserver> observer) = 0;
virtual void detach(std::weak_ptr<IObserver> observer) = 0;
};
// =======================================================================
/**
* The Subject owns some important state
* and notifies observers when the state changes.
*/
class Subject : public ISubject {
private:
std::vector<std::weak_ptr<IObserver>> m_observers;
std::string m_message;
public:
~Subject() override {
std::println("d'tor Subject");
}
/**
* subscription management methods
*/
void attach(std::weak_ptr<IObserver> observer) override {
m_observers.push_back(std::move(observer));
}
void detach(std::weak_ptr<IObserver> observer) override {
// https://stackoverflow.com/questions/10120623/removing-item-from-list-of-weak-ptrs
// C++20: std::erase_if is the modern and cleanest way to implement the erase-remove pattern.
std::erase_if(m_observers, [&observer](const std::weak_ptr<IObserver>& wp) {
return sameOwner(wp, observer);
}
);
}
void setMessage(std::string_view message) {
m_message = message;
notify();
}
/**
* Usually, the subscription logic is only a fraction of what a Subject can
* really do. Subjects commonly hold some important business logic, that
* triggers a notification method whenever something important is about to
* happen (or after it).
*/
void someBusinessLogic() {
std::println("Subject: changing state ...");
setMessage("changing this message");
}
private:
static bool sameOwner(const std::weak_ptr<IObserver>& lhs, const std::weak_ptr<IObserver>& rhs)
{
return !lhs.owner_before(rhs) && !rhs.owner_before(lhs);
}
void notify() {
// clean up expired weak pointers while notifying active observers
std::erase_if(
m_observers,
[this](const std::weak_ptr<IObserver>& wp) {
if (auto sharedPtr = wp.lock()) {
sharedPtr->update(m_message);
return false; // keep, as actively notified.
}
return true; // remove, because expired
}
);
}
};
// ===========================================================================
class Observer : public IObserver {
private:
std::string m_messageFromSubject;
std::size_t m_number;
public:
Observer()
{
static std::size_t nextNumber = 0;
m_number = nextNumber++;
std::println("Observer: {}", m_number);
}
~Observer() override
{
std::println("d'tor Observer ({})", m_number);
}
void update(std::string_view messageFromSubject) override
{
m_messageFromSubject = messageFromSubject;
printInfo();
}
void printInfo() const {
std::println("Observer: new message is available --> \"{}\"", m_messageFromSubject);
}
};
static void example_01() {
Subject subject;
std::shared_ptr<IObserver> observer1{ std::make_shared<Observer>() };
std::shared_ptr<IObserver> observer2{ std::make_shared<Observer>() };
std::shared_ptr<IObserver> observer3{ std::make_shared<Observer>() };
subject.attach(observer1);
subject.attach(observer2);
subject.attach(observer3);
subject.setMessage("Hello World!");
subject.setMessage("Hello World Again");
subject.detach(observer1);
subject.detach(observer2);
subject.detach(observer3);
}
static void example_02() {
std::shared_ptr<Subject> subject{ std::make_shared<Subject>() };
std::shared_ptr<IObserver> observer1{ std::make_shared<Observer>() };
std::shared_ptr<IObserver> observer2{ std::make_shared<Observer>() };
subject->attach(observer1);
subject->attach(observer2);
{
std::shared_ptr<IObserver> observer3{ std::make_shared<Observer>() };
subject->attach(observer3);
subject->setMessage("Hello World!");
}
// Note: Watch contents of 'm_observers' list
// Expired weak_ptr will be cleaned up on next notify()
subject->setMessage("Hello World Again");
subject->detach(observer1);
subject->detach(observer2);
}
}
// ===========================================================================
void test_conceptual_example_01()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
using namespace ConceptualExample_Observer_Pattern;
example_01();
example_02();
}
// ===========================================================================
// End-of-File
// ===========================================================================