Repository navigation
Expand file tree
/
Copy pathobserver.cpp
More file actions
executable file
路69 lines (58 loc) 路 1.71 KB
/
Copy pathobserver.cpp
File metadata and controls
executable file
路69 lines (58 loc) 路 1.71 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
#include "../utils.hpp"
#include <iostream>
#include <map>
class Subscriber {
public:
virtual void onNotify(const char* data) = 0;
};
class DataManager {
public:
void subscribe(const char* key, Subscriber* value) {
subscribers.emplace(key, value);
}
void unsubscribe(const char* key, Subscriber* value) {
auto found = subscribers.equal_range(key);
for (auto el = found.first; el != found.second; ++el)
if (el->second == value) {
subscribers.erase(el);
return;
}
}
void notify(const char* key, const char* data) {
auto found = subscribers.equal_range(key);
for (auto el = found.first; el != found.second; ++el)
el->second->onNotify(data);
}
private:
std::multimap<const char*, Subscriber*> subscribers;
};
class InfoLogger : public Subscriber {
public:
void onNotify(const char* data) override {
std::cout << "[Info]: " << data << std::endl;
}
};
class SymbolLogger : public Subscriber {
public:
SymbolLogger(const char* symbol) : symbol(symbol) {}
void onNotify(const char* data) override {
std::cout << symbol << ' ' << data << ' ' << symbol << std::endl;
}
private:
const char* symbol;
};
namespace utils {
void useObserver() {
InfoLogger infoLogger;
SymbolLogger symbolLogger("***");
DataManager dataManager;
dataManager.subscribe("warn", &infoLogger);
dataManager.subscribe("warn", &symbolLogger);
dataManager.subscribe("error", &infoLogger);
dataManager.notify("error", "1 e");
dataManager.notify("warn", "1 w");
dataManager.unsubscribe("warn", &infoLogger);
dataManager.notify("warn", "2 w");
dataManager.notify("error", "2 e");
}
}