-
Notifications
You must be signed in to change notification settings - Fork 10
/
第二十四章 责任链模式.cpp
94 lines (82 loc) · 2.02 KB
/
第二十四章 责任链模式.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
#include <iostream>
#include <memory>
#include <random>
#include <ctime>
class CHandler
{
public:
virtual ~CHandler() = default;
void SetSuperior(const std::shared_ptr<CHandler> &superior)
{
m_superior = superior;
}
virtual void HandlerRequest(int request)const = 0;
protected:
std::shared_ptr<CHandler> m_superior = nullptr;
};
class CConcreteHandlerA : public CHandler
{
public:
virtual void HandlerRequest(int request)const override
{
if (request < 10)
{
std::cout << "CConcreteHandlerA handle" << request << std::endl;
}
else
{
if (m_superior != nullptr)
{
m_superior->HandlerRequest(request);
}
}
}
};
class CConcreteHandlerB : public CHandler
{
public:
virtual void HandlerRequest(int request)const override
{
if (request < 20)
{
std::cout << "CConcreteHandlerB handle" << request << std::endl;
}
else
{
if (m_superior != nullptr)
{
m_superior->HandlerRequest(request);
}
}
}
};
class CConcreteHandlerC : public CHandler
{
public:
virtual void HandlerRequest(int request)const override
{
if (request < 30)
{
std::cout << "CConcreteHandlerC handle" << request << std::endl;
}
else
{
std::cout << "no handle" << request << std::endl;
}
}
};
int main()
{
std::shared_ptr<CHandler> handlerA = std::make_shared<CConcreteHandlerA>();
std::shared_ptr<CHandler> handlerB = std::make_shared<CConcreteHandlerB>();
std::shared_ptr<CHandler> handlerC = std::make_shared<CConcreteHandlerC>();
handlerA->SetSuperior(handlerB);
handlerB->SetSuperior(handlerC);
std::default_random_engine dre(time(nullptr));
std::uniform_int_distribution<> uid(0, 50);
for (size_t index = 0; index < 20; ++index)
{
handlerA->HandlerRequest(uid(dre));
}
return 0;
}