命令模式
·
Yin灏
/**
* 命令模式
*/
var viewCommand = (function () {
var tpl = {
product: [
"<div>",
'<img src="{#src#}" />',
"<p>{#text#}</p>",
"</div>",
].join(""),
title: [
'<div class="title">',
'<div class="main">',
"<h2>{#title#}</h2>",
"<p>{#tips#}</p>",
"</div>",
"</div>",
].join(""),
},
html = "";
function formateString(str, obj) {
return str.replace(/\{#(\w+)#\}/g, function (match, key) {
return obj[key];
});
}
// 方法集合
var Action = {
// 创建方法
create: function (data, view) {
// 解析数据,如果数据是一个数组
if (data.length) {
for (var i = 0, len = data.length; i < len; i++) {
html += formateString(tpl[view], data[i]);
}
} else {
html += formateString(tpl[view], data);
}
},
// 展示方法
display: function (container, data, view) {
if (data) {
this.create(data, view);
}
document.getElementById(container).innerHTML = html;
html = "";
},
};
// 命令接口
return function excute(msg) {
msg.param =
Object.prototype.toString.call(msg.param) === "[object Array]"
? msg.param
: [msg.param];
Action[msg.command].apply(Action, msg.param);
};
})();
/**
* 大功告成
*/
var productData = [
{
src: "command/02.jpg",
text: "绽放的桃花",
},
{
src: "command/03.jpg",
text: "阳光下的温馨",
},
{
src: "command/04.jpg",
text: "镜头前的绿地",
},
],
titleData = {
title: "夏日里的一片温馨",
tips: "暖暖的温情带给人们家的感受",
};
// 展示一个标题模块
viewCommand({
command: "display",
param: ["title", titleData, "title"],
});
// 创建一个图片
viewCommand({
command: "create",
param: [
{
src: "command/01.jpg",
text: "迎着朝阳的野菊花",
},
"product",
],
});
// 创建多图
viewCommand({
command: "display",
param: ["product", productData, "product"],
});
/**
* 绘图命令
*/
// 实现对象
var CanvasCommand = (function () {
var canvas = document.getElementById("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();
},
// 描边
stroke: function () {
ctx.stroke();
},
};
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 =
Object.prototype.toString.call(msg.param) === "[object Array]"
? msg.param
: [msg.param];
Action[msg.command].apply(Action, msg.param);
}
},
};
})();
// 测试用例
CanvasCommand.excute([
{
command: "fillStyle",
param: "red",
},
{
command: "fillRect",
param: [20, 20, 100, 100],
},
]);