<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>命令模式</title>
</head>
<style>
#show div img{
width: 50%;
height: 500px;
}
</style>
<body>
<div id="show"></div>
<script>
//模块实现模块
let viewCommand =(function () {
let 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) {
// console.log(obj[key]);
return obj[key];
});
}
//方法的集合
let Action ={
create:function (data,view) {
if(data.length){
for(let i =0;i<data.length;i++){
//将格式化的字符串缓存到html中
html += formateString(tpl[view],data[i]);
console.log(html);
}
}else{
//格式化缓存
console.log(html);
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);
}
})();
// viewCommand({
// command:"create",
// param:[{
// src:"http://5b0988e595225.cdn.sohucs.com/images/20181026/0419d2e805484d1f828be3d4d1957339.jpeg",
// text:"初音"
// },'product']
// });
viewCommand({
command:"display",
param:[
'show'
,{
src:"http://5b0988e595225.cdn.sohucs.com/images/20181026/0419d2e805484d1f828be3d4d1957339.jpeg",
text:"初音"
},'product']
});
</script>
</body>
</html>
js 面向对象编程设计模式--命令模式
最新推荐文章于 2020-08-20 11:28:29 发布