-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwith_command.js
More file actions
135 lines (113 loc) · 2.79 KB
/
Copy pathwith_command.js
File metadata and controls
135 lines (113 loc) · 2.79 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* @Author: junchao
* @Date: 2021-01-05 12:09:54
* @LastEditTime: 2021-01-07 15:05:58
* @LastEditors: junchao
* @Description:
* @FilePath: /JavaScriptDesignPatterns/command/with_command.js
* @可以输入预定的版权声明、个性签名、空行等
*/
// 烧烤店的实现
// Receiver 接收者类 厨师,拥有烤羊肉串,烤鸡翅等能力
class Cooker {
execute(action) {
console.log(`厨房收到订单: 开始${action}`)
switch (action) {
case "烤羊肉串":
this.bakeMutton();
break;
case "烤鸡翅":
this.bakeChickenWing();
break;
default:
console.log(`厨房没有${action}了,请点其他的菜`);
break;
}
}
// 烤羊肉串
bakeMutton() {
setTimeout(() => {
console.log('羊肉串烤好了,可以给客人上菜了');
}, 500);
}
// 烤鸡翅
bakeChickenWing() {
setTimeout(() => {
console.log('鸡翅烤好了,可以给客人上菜了');
}, 1000);
}
}
// command 命令对象类
class Command {
constructor(receiver) {
this.receiver = receiver;
}
execute(action) {
this.receiver.execute(action);
}
}
// ConcreteCommand
// 烤羊肉串的命令
class BakeMuttonCommand extends Command {
constructor(receiver) {
super(receiver);
}
execute() {
this.receiver.execute('烤羊肉串');
}
}
// 烤牛肉串的命令
class BakeBeefCommand extends Command {
constructor(receiver) {
super(receiver);
}
execute() {
this.receiver.execute('烤牛肉串');
}
}
// 烤鸡翅的命令
class BakeChickenWingCommand extends Command {
constructor(receiver) {
super(receiver);
}
execute() {
this.receiver.execute('烤鸡翅');
}
}
// Invoker 发布者 服务员
class Invoker {
constructor() {
this.orders = [];
}
// 添加菜品
setOrder(type, command) {
this.orders.push(command);
console.log(`${Date.now()} 下单 ${type}`);
}
// 取消菜品
cancelOrder(type, command) {
let index = this.orders.indexOf(command);
this.orders.splice(index, 1);
console.log(`${Date.now()} 取消下单 ${type}`)
}
// 向后厨下单
notify() {
console.log('向后厨下单');
this.orders.forEach(element => {
element.execute();
});
}
}
let cooker = new Cooker();
let bakeMuttonCommand = new BakeMuttonCommand(cooker);
let bakeBeefCommand = new BakeBeefCommand(cooker);
let bakeChickenWingCommand = new BakeChickenWingCommand(cooker);
let waiter = new Invoker();
waiter.setOrder('烤羊肉串', bakeMuttonCommand);
waiter.setOrder('烤羊肉串', bakeMuttonCommand);
waiter.setOrder('烤牛肉串', bakeBeefCommand);
waiter.setOrder('烤鸡翅', bakeChickenWingCommand);
waiter.cancelOrder('烤羊肉串', bakeMuttonCommand);
// setTimeout(() => {
waiter.notify();
// }, 1000);