-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.cpp
101 lines (88 loc) · 2.47 KB
/
main.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* @FileName : main.cpp
* @CreateAt : 2022/11/27
* @Author : Inno Fang
* @Email : [email protected]
* @Description:
*/
#include <iostream>
#include <string>
#include <vector>
class Handler {
public:
virtual Handler *next(Handler *Handler) = 0;
virtual std::string handle(const std::string &request) = 0;
};
class AbstractHandler: public Handler {
public:
AbstractHandler() : _next_handler(nullptr) {}
Handler *next(Handler *handler) override {
_next_handler = handler;
return _next_handler;
}
std::string handle(const std::string &request) override {
if (_next_handler) {
return _next_handler->handle(request);
}
return {};
}
private:
Handler *_next_handler;
};
class MonkeyHandler : public AbstractHandler {
public:
std::string handle(const std::string &request) override {
if (request == "Banana") {
return "Monkey: I'll eat the " + request + ".\n";
} else {
return AbstractHandler::handle(request);
}
}
};
class SquirrelHandler : public AbstractHandler {
public:
std::string handle(const std::string &request) override {
if (request == "Nut") {
return "Squirrel: I'll eat the " + request + ".\n";
} else {
return AbstractHandler::handle(request);
}
}
};
class DogHandler : public AbstractHandler {
public:
std::string handle(const std::string &request) override {
if (request == "MeatBall") {
return "Dog: I'll eat the " + request + ".\n";
} else {
return AbstractHandler::handle(request);
}
}
};
void ClientCode(Handler &handler) {
std::vector<std::string> food = {"Nut", "Banana", "Cup of coffee"};
for (const std::string &f : food) {
std::cout << "Client: Who wants a " << f << "?\n";
const std::string result = handler.handle(f);
if (!result.empty()) {
std::cout << " " << result;
} else {
std::cout << " " << f << " was left untouched.\n";
}
}
}
int main() {
auto *monkey = new MonkeyHandler;
auto *squirrel = new SquirrelHandler;
auto *dog = new DogHandler;
monkey->next(squirrel)->next(dog);
std::cout << "Chain: Monkey > Squirrel > Dog\n\n";
ClientCode(*monkey);
std::cout << "\n";
std::cout << "Subchain: Squirrel > Dog\n\n";
ClientCode(*squirrel);
delete monkey;
delete squirrel;
delete dog;
return 0;
}