-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain.cpp
102 lines (88 loc) · 2.35 KB
/
chain.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
102
#include <iostream>
#include <string>
#include <vector>
/***
The Handler interface declares a method for building the chain of handlers
***/
class Handler
{
public:
virtual std::string handle(const std::string &request) const = 0;
virtual Handler* setNext(Handler* handler) = 0;
};
class AbstractHandler: public Handler
{
private:
Handler *_handler{nullptr};
public:
virtual std::string handle(const std::string &request) const override
{
if(_handler)
return _handler->handle(request);
return "";
}
virtual Handler* setNext(Handler *handler) override
{
_handler = handler;
// return the handler from here let us links handlers like this:
// handler1->setNext(handler2)->setNext(handler3)
return handler;
}
};
/***
All Concrete Handlers either handle a request or pass it to the next handler
***/
class MonkeyHandler: public AbstractHandler
{
public:
std::string handle(const std::string &request) const 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) const 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) const override
{
if(request == "meatball")
return "Dog: I'll eat the " + request + ".\n";
else return AbstractHandler::handle(request);
}
};
/***
The client code not even awares that the handler is part of a chain
***/
void ClientCode(Handler *handler)
{
std::vector<std::string> food = {"nut", "banana", "coffee"};
for(const std::string &f : food)
{
std::cout << "Client: Who wants a " << f << "?\n";
std::cout << handler->handle(f) << std::endl;
}
}
int main()
{
MonkeyHandler *monkey = new MonkeyHandler();
SquirrelHandler *squirrel = new SquirrelHandler();
DogHandler *dog = new DogHandler();
dog->setNext(squirrel)->setNext(monkey);
ClientCode(dog);
delete monkey;
delete squirrel;
delete dog;
return 0;
}