0%

C++ 观察者设计模式

观察者模式

观察者模式实现

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
#include <iostream>
#include <memory>
#include <string>
#include <vector>

class observer;
class subscriber : public std::enable_shared_from_this<subscriber> {
public:
subscriber(const std::string& user_name) : user_name_(user_name) {
}

void callback(const std::string& str) {
std::cout << user_name_ << ": " << str << std::endl;
}
private:
std::string user_name_;
};

class observer {
public:
void boardcast(const std::string& message) {
for (auto it = vec.begin(); it != vec.end();) {
auto sp = it->lock();
if (sp) {
sp->callback(message);
it++;
} else {
it = vec.erase(it);
}
}
}

void regist(std::weak_ptr<subscriber> wp) {
if (wp.lock()) {
vec.push_back(wp);
}
}
private:
std::vector<std::weak_ptr<subscriber>> vec;
};

int main() {
auto ob = std::make_shared<observer>();
auto sp1 = std::make_shared<subscriber> ("subscriber1");
ob->regist(sp1->weak_from_this());
auto sp2 = std::make_shared<subscriber> ("subscriber2");
ob->regist(sp2->weak_from_this());
{
auto sp3 = std::make_shared<subscriber> ("subscriber3");
ob->regist(sp3->weak_from_this());
auto sp4 = std::make_shared<subscriber> ("subscriber4");
ob->regist(sp4->weak_from_this());
ob->boardcast("start boardcast!");
}
ob->boardcast("boardcast again!");
return 0;
}