-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchain_of_responsibility.cpp
More file actions
88 lines (70 loc) · 1.85 KB
/
chain_of_responsibility.cpp
File metadata and controls
88 lines (70 loc) · 1.85 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
#include <iostream>
#include <string>
using namespace std;
class IHandler {
private:
// 下一个处理人
IHandler* _next;
public:
explicit IHandler(IHandler* next) : _next(next) {}
virtual ~IHandler() = default;
// 判断是否由自己处理
virtual bool pred(const string& event) = 0;
// 处理请求
virtual void deal(const string& event) = 0;
// 如果该由自己处理, 则直接处理请求
// 如果不该由自己处理, 转发给下一位处理人
void process(const string& event) {
if(pred(event)) {
deal(event);
} else {
_next->process(event);
}
}
};
// 第一个处理人
class Handler1 : public IHandler {
public:
explicit Handler1(IHandler* next) : IHandler(next) {}
bool pred(const string& event) override {
return event.empty();
}
void deal(const string& event) override {
cout << "event is empty" << endl;
}
};
// 第二个处理人
class Handler2 : public IHandler {
public:
explicit Handler2(IHandler* next) : IHandler(next) {}
bool pred(const string& event) override {
return event.size() <= 5;
}
void deal(const string& event) override {
cout << event << ": small event" << endl;
}
};
// 默认处理人
class Handler3 : public IHandler {
public:
explicit Handler3() : IHandler(nullptr) {}
bool pred(const string& event) override {
return true;
}
void deal(const string& event) override {
cout << event << ": big event" << endl;
}
};
int main() {
// 构建职责链
Handler3 handler3{};
Handler2 handler2(&handler3);
Handler1 handler1(&handler2);
string event1;
handler1.process(event1);
string event2 = "abc";
handler1.process(event2);
string event3 = "abcdefgh";
handler1.process(event3);
return 0;
}