-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibrary_example.cpp
More file actions
353 lines (268 loc) · 10.2 KB
/
Copy pathlibrary_example.cpp
File metadata and controls
353 lines (268 loc) · 10.2 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
#include "delegate.hpp"
class Library;
class CollectionBase;
class CatalogItem {
public:
explicit CatalogItem(std::uint64_t id) : id_(id) {}
virtual ~CatalogItem() = default;
std::uint64_t id() const { return id_; }
Library* library() const { return library_; }
virtual std::string description() const = 0;
private:
std::uint64_t id_{0};
Library* library_{nullptr};
friend class Library;
};
struct CollectionEvent {
const CollectionBase* sender{nullptr};
CatalogItem* item{nullptr};
};
class CollectionBase {
public:
using EventSignal = Delegate<void(const CollectionEvent&)>;
virtual ~CollectionBase() = default;
EventSignal added;
EventSignal removed;
virtual const std::string& name() const = 0;
virtual std::vector<CatalogItem*> snapshot() const = 0;
};
template <typename T>
class ObservableCollection : public CollectionBase {
public:
static_assert(std::is_base_of_v<CatalogItem, T>, "T must derive from CatalogItem");
virtual ~ObservableCollection() = default;
virtual bool add(std::unique_ptr<T> item) {
if (!item) {
std::cout << "[ObservableCollection] null item, skip" << '\n';
return false;
}
T* raw_item = item.get();
items_.push_back(std::move(item));
added.broadcast(CollectionEvent{this, raw_item});
return true;
}
const std::vector<std::unique_ptr<T>>& items() const { return items_; }
std::vector<CatalogItem*> snapshot() const override {
std::vector<CatalogItem*> items;
items.reserve(items_.size());
for (const std::unique_ptr<T>& item : items_) {
items.push_back(item.get());
}
return items;
}
protected:
template <typename Predicate>
bool contains_if(Predicate&& predicate) const {
return std::any_of(items_.begin(), items_.end(),
[&predicate](const std::unique_ptr<T>& item) { return predicate(*item); });
}
template <typename Predicate>
bool erase_if(Predicate&& predicate) {
auto it = std::find_if(items_.begin(), items_.end(),
[&predicate](const std::unique_ptr<T>& item) { return predicate(*item); });
if (it == items_.end()) {
return false;
}
std::unique_ptr<T> removed_item = std::move(*it);
items_.erase(it);
removed.broadcast(CollectionEvent{this, removed_item.get()});
return true;
}
private:
std::vector<std::unique_ptr<T>> items_;
};
class Book : public CatalogItem {
public:
Book(std::uint64_t id, std::string title) : CatalogItem(id), title_(std::move(title)) {}
const std::string& title() const { return title_; }
std::string description() const override { return std::to_string(id()) + " - " + title_; }
private:
std::string title_;
};
class Magazine : public CatalogItem {
public:
Magazine(std::uint64_t id, std::string name, int issue) : CatalogItem(id), name_(std::move(name)), issue_(issue) {}
std::string description() const override {
return std::to_string(id()) + " - " + name_ + " (issue " + std::to_string(issue_) + ")";
}
private:
std::string name_;
int issue_{0};
};
class BookShelf : public ObservableCollection<Book> {
public:
explicit BookShelf(std::string name) : name_(std::move(name)) {}
bool add(std::unique_ptr<Book> book) override {
if (book && contains_id(book->id())) {
std::cout << "[BookShelf] duplicate id, skip: " << book->id() << '\n';
return false;
}
return ObservableCollection<Book>::add(std::move(book));
}
bool add_book(std::uint64_t id, std::string title) { return add(std::make_unique<Book>(id, std::move(title))); }
bool remove_book(std::uint64_t id) {
if (!this->erase_if([id](const Book& book) { return book.id() == id; })) {
std::cout << "[BookShelf] missing id, skip remove: " << id << '\n';
return false;
}
return true;
}
const std::string& name() const override { return name_; }
private:
bool contains_id(std::uint64_t id) const {
return this->contains_if([id](const Book& book) { return book.id() == id; });
}
std::string name_;
};
class MagazineRack : public ObservableCollection<Magazine> {
public:
explicit MagazineRack(std::string name) : name_(std::move(name)) {}
bool add(std::unique_ptr<Magazine> magazine) override {
if (magazine && contains_id(magazine->id())) {
std::cout << "[MagazineRack] duplicate id, skip: " << magazine->id() << '\n';
return false;
}
return ObservableCollection<Magazine>::add(std::move(magazine));
}
bool add_magazine(std::uint64_t id, std::string name, int issue) {
return add(std::make_unique<Magazine>(id, std::move(name), issue));
}
bool remove_magazine(std::uint64_t id) {
if (!this->erase_if([id](const Magazine& magazine) { return magazine.id() == id; })) {
std::cout << "[MagazineRack] missing id, skip remove: " << id << '\n';
return false;
}
return true;
}
const std::string& name() const override { return name_; }
private:
bool contains_id(std::uint64_t id) const {
return this->contains_if([id](const Magazine& magazine) { return magazine.id() == id; });
}
std::string name_;
};
class Library {
public:
template <typename T>
void register_collection(ObservableCollection<T>& collection) {
auto* base = static_cast<CollectionBase*>(&collection);
if (subscriptions_.count(base) != 0) {
std::cout << "[Library] collection already registered: " << base->name() << '\n';
return;
}
Subscription subscription;
subscription.add_handle = base->added.add(this, &Library::handle_add);
subscription.remove_handle = base->removed.add(this, &Library::handle_remove);
subscriptions_.emplace(base, subscription);
std::cout << "[Library] register_collection: " << base->name() << '\n';
for (CatalogItem* item : base->snapshot()) {
load_existing_item(*base, *item);
}
print_index_size();
}
template <typename T>
void unregister_collection(ObservableCollection<T>& collection) {
auto* base = static_cast<CollectionBase*>(&collection);
auto it = subscriptions_.find(base);
if (it == subscriptions_.end()) {
std::cout << "[Library] collection is not registered: " << base->name() << '\n';
return;
}
base->added.remove(it->second.add_handle);
base->removed.remove(it->second.remove_handle);
subscriptions_.erase(it);
std::cout << "[Library] unregister_collection: " << base->name() << '\n';
for (CatalogItem* item : base->snapshot()) {
remove_item(*base, *item, "remove because collection was unregistered");
}
print_index_size();
}
private:
using EventSignal = CollectionBase::EventSignal;
struct Subscription {
EventSignal::Handle add_handle{EventSignal::InvalidHandle};
EventSignal::Handle remove_handle{EventSignal::InvalidHandle};
};
struct IndexEntry {
std::string collection_name;
std::string description;
};
void load_existing_item(const CollectionBase& collection, CatalogItem& item) {
add_item(collection, item, "load existing item");
}
void handle_add(const CollectionEvent& event) {
if (!event.sender || !event.item) {
return;
}
add_item(*event.sender, *event.item, "noticed added");
print_index_size();
}
void handle_remove(const CollectionEvent& event) {
if (!event.sender || !event.item) {
return;
}
remove_item(*event.sender, *event.item, "noticed removed");
print_index_size();
}
void add_item(const CollectionBase& collection, CatalogItem& item, const std::string& reason) {
if (item.library_ != nullptr && item.library_ != this) {
std::cout << "[Library] item already belongs to another library: " << item.description() << '\n';
return;
}
item.library_ = this;
index_[item.id()] = IndexEntry{collection.name(), item.description()};
std::cout << "[Library] " << reason << " from " << collection.name() << ": " << item.description() << '\n';
}
void remove_item(const CollectionBase& collection, CatalogItem& item, const std::string& reason) {
auto it = index_.find(item.id());
if (it == index_.end()) {
return;
}
item.library_ = nullptr;
std::cout << "[Library] " << reason << " from " << collection.name() << ": " << item.description() << '\n';
index_.erase(it);
}
void print_index_size() const { std::cout << "[Library] indexed item count: " << index_.size() << '\n'; }
std::unordered_map<CollectionBase*, Subscription> subscriptions_;
std::unordered_map<std::uint64_t, IndexEntry> index_;
};
int main() {
BookShelf shelf("Fiction Shelf");
shelf.add_book(101, "Dune");
shelf.add_book(102, "Foundation");
MagazineRack rack("Magazine Rack");
rack.add_magazine(201, "Science Weekly", 42);
rack.add_magazine(202, "Tech Monthly", 7);
Library library;
std::cout << "--- Register book collection after it already has data ---" << '\n';
library.register_collection(shelf);
std::cout << '\n' << "--- Register magazine collection after it already has data ---" << '\n';
library.register_collection(rack);
std::cout << '\n' << "--- Add one more book after registration ---" << '\n';
shelf.add_book(103, "Hyperion");
std::cout << '\n' << "--- Try duplicate book id, derived class should reject it ---" << '\n';
shelf.add(std::make_unique<Book>(103, "Duplicate Hyperion"));
std::cout << '\n' << "--- Add one more magazine after registration ---" << '\n';
rack.add_magazine(203, "History Digest", 3);
std::cout << '\n' << "--- Remove one book after registration ---" << '\n';
shelf.remove_book(102);
std::cout << '\n' << "--- Remove one magazine after registration ---" << '\n';
rack.remove_magazine(201);
std::cout << '\n' << "--- Unregister book collection ---" << '\n';
library.unregister_collection(shelf);
std::cout << '\n' << "--- Add book after unregister, Library should stay silent for books ---" << '\n';
shelf.add_book(104, "Snow Crash");
std::cout << '\n' << "--- Magazine collection is still registered ---" << '\n';
rack.add_magazine(204, "Design Review", 11);
std::cout << '\n' << "--- Unregister magazine collection ---" << '\n';
library.unregister_collection(rack);
return 0;
}