/
index.ts
105 lines (82 loc) · 2.38 KB
/
index.ts
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
103
104
105
// https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
namespace ChainOfResponsibilityPattern {
abstract class Handler {
private nextHandler: Handler;
public setNext(handler: Handler): Handler {
this.nextHandler = handler;
return handler;
}
public handleRequest(request: string): string {
if (this.checkHandle(request)) {
return this.handle(request);
} else if (this.nextHandler) {
return this.nextHandler.handleRequest(request);
}
return null;
}
protected abstract checkHandle(request: string): boolean;
protected abstract handle(request: string): string;
}
class MonkeyHandler extends Handler {
checkHandle(request: string): boolean {
return request === "Banana";
}
handle(request: string): string {
return `Monkey: I'll eat the ${request}.`;
}
}
class CatHandler extends Handler {
checkHandle(request: string): boolean {
return request === "Fish";
}
handle(request: string): string {
return `Cat: I'll eat the ${request}.`;
}
}
class DogHandler extends Handler {
checkHandle(request: string): boolean {
return request === "Bone";
}
handle(request: string): string {
return `Dog: I'll eat the ${request}.`;
}
}
// Client code
function clientCode(handler: Handler) {
const foods = ["Bone", "Banana", "Cup of coffee"];
for (const food of foods) {
console.log(`Client: Who wants a ${food}?`);
const result = handler.handleRequest(food);
if (result) {
console.log(` ${result}`);
} else {
console.log(` ${food} was left untouched.`);
}
}
}
const monkey = new MonkeyHandler();
const cat = new CatHandler();
const dog = new DogHandler();
monkey.setNext(cat).setNext(dog);
console.log("Chain: Monkey > Cat > Dog\n");
clientCode(monkey);
console.log("");
console.log("SubChain: Cat > Dog\n");
clientCode(cat);
// Output
/*
Chain: Monkey > Cat > Dog
Client: Who wants a Bone?
Dog: I'll eat the Bone.
Client: Who wants a Banana?
Monkey: I'll eat the Banana.
Client: Who wants a Cup of coffee?
Cup of coffee was left untouched.
SubChain: Cat > Dog
Client: Who wants a Bone?
Dog: I'll eat the Bone.
Client: Who wants a Banana?
Banana was left untouched.
Client: Who wants a Cup of coffee?
*/
}