-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain_of_responsibility.cpp
55 lines (45 loc) · 1.11 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
#include <iostream>
class Handle {
public:
virtual ~Handle() = default;
virtual void handleRequest() = 0;
Handle *successor() const {
return _succ;
}
protected:
Handle(Handle *succ = nullptr): _succ(succ) {}
private:
Handle *_succ;
};
class ConcreteHandleA: public Handle {
public:
ConcreteHandleA(Handle *succ = nullptr): Handle(succ) {}
void handleRequest() override {
if (this->successor() != nullptr) {
std::cout << "ConcreteHandleA Successor" << std::endl;
successor()->handleRequest();
} else {
std::cout << "ConcreteHandleA handleRequest" << std::endl;
}
}
};
class ConcreteHandleB: public Handle {
public:
ConcreteHandleB(Handle *succ = nullptr): Handle(succ) {}
void handleRequest() override {
if (this->successor() != nullptr) {
std::cout << "ConcreteHandleB Successor" << std::endl;
successor()->handleRequest();
} else {
std::cout << "ConcreteHandleB handleRequest" << std::endl;
}
}
};
int main() {
Handle *handler1 = new ConcreteHandleA();
Handle *handler2 = new ConcreteHandleB(handler1);
handler2->handleRequest();
delete handler1;
delete handler2;
return 0;
}