命令模式

命令模式把一个请求或者操作封装到一个对象中。 命令模式允许系统使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能

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

// 命令
interface Command {
execute: () => void;
}

// 执行者Amy
class Amy {
// 跳舞
public dance() {
console.log('我是Amy,我在跳舞');
}

// 唱歌
public sing() {
console.log('我是Amy,我在唱歌');
}
}

// 执行者Jonny
class Jonny {
// 阅读
public read() {
console.log('我是Jonny,我在阅读');
}

//吃饭
public eatingRice() {
console.log('我是Jonny,我在吃饭');
}
}

class Command1 implements Command {
private r1: Jonny = new Jonny;
private r2: Amy = new Amy;

public execute() {
this.r1.eatingRice();
this.r2.dance();
}
}


class Command2 implements Command{
private r1: Jonny = new Jonny;
private r2: Amy = new Amy;

public execute(){
this.r1.read();
this.r2.sing();
}
}

(function main(){
const c1 = new Command1();
const c2 = new Command2();
c1.execute();
c2.execute();
})();