-
Notifications
You must be signed in to change notification settings - Fork 0
/
commandModeByObjectOriented.html
59 lines (55 loc) · 2.63 KB
/
commandModeByObjectOriented.html
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
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<title>用面向对象的方式来编写一段命令模式</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
</head>
<body>
<button id="execute">点击我执行命令</button>
<button id="undo">点击我执行命令</button>
<script>
var Tv = {
open: function () {
console.log('打开电视机');
},
close: function () {
console.log('关上电视机');
}
};
///////////////////////////////////////////////////////////
var OpenTvCommand = function (receiver) { //
this.receiver = receiver; //
}; //
OpenTvCommand.prototype.execute = function () { //
this.receiver.open(); // 执行命令,打开电视机 //
}; //
OpenTvCommand.prototype.undo = function () { //
this.receiver.close(); // 撤销命令,关闭电视机 //
}; //
///////////////////////////////////////////////////////////
var createCommand = function (receiver) { //
var execute = function () { //
return receiver.open(); // 执行命令,打开电视机 //
} //
var undo = function () { //
return receiver.close(); // 执行命令,关闭电视机 //
} //
return { //
execute: execute, //
undo: undo //
} //
}; //
///////////////////////////////////////////////////////////
var setCommand = function (command) {
document.getElementById('execute').onclick = function () {
command.execute(); // 输出:打开电视机
}
document.getElementById('undo').onclick = function () {
command.undo(); // 输出:关闭电视机
}
};
setCommand(new OpenTvCommand(Tv));
</script>
</body>
</html>