命令模式

命令模式: 将请求与实现解耦并封装成独立对象, 从而使不同的请求对客户端的实现参数化.

封装canvas绘图

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
var canvasCommand = (function () {
// 获取canvas
var canvas = document.getElementById('canvas')
// canvas元素的上下文引用对象缓存在命令对象的内部
var ctx = canvas.getContext('2d')
// 内部方法
var Action = {
// 填充色彩
fillstyle: function (c) {
ctx.fillstyle = c
},
// 填充矩形
fillRect: function (x, y, width, height) {
ctx.fillRect(x, y, width, height)
},
// 描边色彩
strokestyle: function (c) {
ctx.strokestyle = c
},
// 描边矩形
strokeRect: function (x, y, width, height) {
ctx.strokeRect(x, y, width, height)
},
// 填充字体
fillText: function (text, x, y) {
ctx.fillText(text, x, y)
},
// 开启路径
beginPath: function () {
ctx.beginPath()
},
// 移动画笔触点
moveTo: function (x, y) {
ctx.moveTo(x, y)
},
// 画笔连线
lineTo: function (x, y) {
ctx.lineTo(x, y)
},
// 绘制弧线
arc: function (x, y, r, begin, end, dir) {
ctx.arc(x, y, r, begin, end, dir)
},
// 填充
fill: function () {
ctx.fill()
ctx.stroke()
},
// 描边
stroke: function () {},
}
return {
// 命令接口
excute: function (msg) {
// 如果没有指令返回
if (!msg) {
return
}
// 如果命令是一个数组
if (msg.length) {
// 遍历执行多个命令
for (var i = 0, len = msg.length; i < len; i++) {
arguments.callee(msg[i])
}
} else {
// 执行一个命令
// 如果msg.param不是一个数组, 将其转化为数组, apply第二个参数要求格式
msg.param =
Object.prototype.toString.call(msg.param) === '[object Array]'
? msg.param
: [msg.param]
// Action 内部调用的方法可能引用this, 为保证作用域中this指向正确, 故传入Action
Action[msg.command].apply(Action, msg.param)
}
},
}
})()

测试

1
2
3
4
canvasCommand.excute([
{ command: 'fillstyle', param: 'red' },
{ command: 'fillRect', param: [20, 20, 100, 100] },
])