-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path10-命令模式.js
156 lines (131 loc) · 2.71 KB
/
10-命令模式.js
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/*
把请求封装成命令对象,从而分离请求发起者和接收者之间的耦合关系,在命令被执行之前,可以预先往命令对象中植入命令的接收者
提供相同的excute执行方法
发起命令者 => 执行的命令对象 => 接收者(具体执行命令操作对象)
应用场景: 富文本编辑器、浏览器封装的命令对象
*/
// e.g1
const setCommand = (target, command) => {
target.onclick = () => {
command.execute();
}
}
// 增加菜单
const menuBar = {
execute () {
console.log('update...');
}
}
const addMenu = {
execute () {
console.log('add...');
}
}
setCommand('btn1', menuBar);
setCommand('btn2', addMenu);
// e.g2
// 撤销和重做
const Jeffery = {
attack () {
console.log('attack...', '攻击');
},
defense () {
console.log('defense...', '防御');
},
jump () {
console.log('jump...', '跳跃');
},
crouch () {
console.log('crouch...', '蹲下')
}
}
const commands = {
119: 'jump', // W
115: 'crouch', // S
97: 'defense', // A
100: 'attack' // D
}
const makeCommand = (receiver, state) => {
return () => {
receiver[state]();
}
}
const commandStack = [];
document.onkeypress = (e) => {
const keyCode = e.keyCode;
const command = makeCommand(Jeffery, commands[keyCode]);
if (command) {
command();
commandStack.push(command);
}
}
document.getElementById('replay').onclick = () => {
const command;
while(command = commandStack.shift()) {
command();
}
}
// 宏命令: 使用add方法添加一组命令到堆栈,并一次性执行完所有命令
const closeDoor = {
execute () {
console.log('关门...');
}
}
const openPc = {
execute () {
console.log('打开电脑...');
}
}
const openQQ = {
execute () {
console.log('打开QQ')
}
}
const MacroCommand = () => {
return {
commandsList: [],
add (command) {
this.commandsList.push(command)
},
execute () {
for (let i = 0, len = this.commandsList.length; i < len; i++) {
this.commandsList[i].execute();
}
}
}
}
const macroCommand = MacroCommand()
// 添加命令
macroCommand.add(closeDoor)
macroCommand.add(openPc);
macroCommand.add(openQQ);
// 执行命令
makeCommand.execute();
// e.g3
class Receiver {
exec () {
console.log('执行')
}
}
class Command {
constructor (receiver) {
this.receiver = receiver
}
cmd () {
console.log('触发命令')
this.receiver.exec()
}
}
class Invoker {
constructor (command) {
this.command = command
}
invoke () {
console.log('开始')
this.command.cmd()
}
}
let soldier = new Receiver()
let trumpleter = new Command(soldier)
let general = new Invoker(trumpleter)
general.invoke()