-
Notifications
You must be signed in to change notification settings - Fork 55
/
chain_of_responsibility.cpp
73 lines (61 loc) · 1.33 KB
/
chain_of_responsibility.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
71
72
73
#include <cstdint>
#include <iostream>
#include <memory>
#include <utility>
namespace jc {
class Handler {
public:
virtual void Process(std::int32_t i) {
if (p_) {
p_->Process(i);
} else {
std::cout << i << "can't be processed\n";
}
}
void SetNext(std::shared_ptr<Handler> p) { p_ = std::move(p); }
virtual ~Handler() = default;
private:
std::shared_ptr<Handler> p_;
};
class A : public Handler {
public:
void Process(std::int32_t i) override {
if (i < 10) {
std::cout << i << " processed by A\n";
} else {
Handler::Process(i);
}
}
};
class B : public Handler {
public:
void Process(std::int32_t i) override {
if (i < 100) {
std::cout << i << " processed by B\n";
} else {
Handler::Process(i);
}
}
};
class C : public Handler {
public:
void Process(std::int32_t i) override {
if (i < 1000) {
std::cout << i << " processed by C\n";
} else {
Handler::Process(i);
}
}
};
} // namespace jc
int main() {
auto a = std::make_shared<jc::A>();
auto b = std::make_shared<jc::B>();
auto c = std::make_shared<jc::C>();
a->SetNext(b);
b->SetNext(c);
a->Process(9); // 9 processed by A
a->Process(999); // 999 processed by C
a->Process(99); // 99 processed by B
a->Process(9999); // 9999 can't be processed
}