javascript设计模式(一)命令模式Command
1.将请求与实现解耦成独立的对象,从而使不通过的请求与客户端实现参数化。
//canvas命令模式 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,bggin,end,dir){ ctx.arc(x,y,r,bggin,end,dir) }, closePath:function(){ ctx.closePath(); }, fill:function(){ ctx.fill(); }, stroke:function(){ ctx.stroke(); } } return { excute:function(msg){ if(!msg){ return } if(msg.length){ for(var i=0;i<msg.length;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]} ]); CanvasCommand.excute([ {command:'strokeStyle',param:'green'}, {command:'strokeRect',param:[20,20,300,300]} ]); CanvasCommand.excute([ {command:'strokeStyle',param:'green'}, {command:'strokeRect',param:[20,20,300,300]} ]); CanvasCommand.excute([ {command:'fillStyle',param:'yellow'}, {command:'beginPath',param:[]}, {command:'arc',param:[100,100,60,0,Math.PI,true]}, {command:'closePath',param:[]}, {command:'fill',param:[]} ]);