-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobserver.cpp
70 lines (58 loc) · 1.38 KB
/
observer.cpp
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
#include <iostream>
#include <string>
#include <list>
#include <utility>
template<class T>
class Observer {
public:
virtual void handleEvent(const T &) = 0;
};
class SupervisedObject {
public:
void add(Observer<SupervisedObject> &observer) {
_observers.push_back(&observer);
}
void remove(Observer<SupervisedObject> &observer) {
_observers.remove(&observer);
}
const std::string &get() const {
return _string;
}
void set(std::string str) {
_string = std::move(str);
_notify();
}
private:
std::string _string = "";
std::list<Observer<SupervisedObject> *> _observers{};
void _notify() {
for (auto &_observer : _observers) {
_observer->handleEvent(*this);
}
}
};
class Reflector: public Observer<SupervisedObject> {
public:
void handleEvent(const SupervisedObject &object) override {
std::cout << "Value: " << object.get() << std::endl;
}
};
class Counter: public Observer<SupervisedObject> {
public:
void handleEvent(const SupervisedObject &object) override {
std::cout << "Length: " << object.get().length() << std::endl;
}
};
int main() {
SupervisedObject supervisedObject;
Reflector observerA;
Counter observerB;
supervisedObject.add(observerA);
supervisedObject.set("Hello, World!");
std::cout << std::endl;
supervisedObject.remove(observerA);
supervisedObject.add(observerB);
supervisedObject.set("World, Hello!");
std::cout << std::endl;
return 0;
}