JavaScript设计模式之命令模式实例分析
本文实例讲述了javascript设计模式之命令模式。分享给大家供大家参考,具体如下:
第一,命令模式:
(1)用于消除调用者和接收者之间直接的耦合的模式,并且可以对(调用这个过程进行留痕操作)
(2)真的不要乱用这个模式,以为他使你简单调用写法变得非常的复杂和有些难以理解。
(3)你的业务出现了 (回退操作)(重做操作)的需求的时候你就要考虑使用这个模式了。
命令的原理:
一种情况为发出者直接作用于执行者,这样耦合度很高,另外一种情况为,在发出者和执行者之间增加一个用存储命令的命令访问库也即命令命令模式。
第二,现在我们通过一个需求来学习该模式
需求为:
1.有一个"添加流程的按钮"单击的时候 就会添加一个新的文本当做流程的描述
2.有"返回","重做" 2个按钮来完成相应的任务。
第三,界面为
<body> <input type="text" id="flow"> <input type="button" value="添加新流程" onclick="api.addflow()"> <br> <input type="button" value="ctrl+z回退" onclick="api.ret()"> <input type="button" value="ctrl+z+x重做" onclick="api.again()"> <div id= "div01"></div> <script src="js/设计模式第三部分/命令模式/keymaster.min.js"></script> <script src="js/设计模式第三部分/命令模式/uuid.js"></script> <script src="js/设计模式第三部分/命令模式/(18)命令模式.js"></script> </body>
效果为,
根据上述图我们逐步完成
步骤一,定义主应用程序----接收者
function manager() { this.addflow=function (id,value) { //1.得到目标节点 var div=document.getelementbyid("div01"); var newflow=document.createelement("div"); newflow.setattribute("id",id); newflow.innerhtml=value; div.appendchild(newflow); } }
步骤二,为对象(执行者)建立命令访问库 ---意思是可以通过extcute方法访问到addflow方法
manager.prototype.extcute=(function () { /*command 命令对象 * */ return function (command) { return this[command.method](command.id,command.value); } })();
步骤三,初始化主类
var ma = new manager();//可以用该对象,调用其的东西 //用于存储"调用对象命令的"集合 var commands = new array(); //集合的游标--初始化在末尾 var index = commands.length;
步骤四,客户端----发出者
var api=function () { this.addflow=function () { //把调用封装起来 var command={ method:"addflow", id:new uuid().createuuid(),//产生id的插件 value:document.getelementbyid("flow").value }; //把调用对象保存起来,用于回退和重做作用 commands.push(command); //重新定位游标---赋值记录 index = commands.length; //调用 ma.extcute(command); }; /** * 用于返回的方法 */ this.ret=function () { if(index-1<0){ alert("已经到了最后一步了..."); }else { var all=document.getelementbyid("div01").childnodes; document.getelementbyid("div01").removechild(all[all.length-1]); index=index-1; } }; /** * 用于重做的方法 */ this.again=function () { if(index>=commands.length){ alert("已经到了最前面一步了,不能进行重做..."); }else { var command=commands[index];//获取当前的命令位置 ma.extcute(command); index=index+1; } } }
步骤五,实例化客户端
api=new api();//实例化
这样html中的事件就可以起作用了。
在这里我们使用插件来让其功能支持自定义的键盘事件,插件名称为:keymaster.js
首先,如html中一样引入文件,
然后值调用key添加自定义的键盘事件
//添加支持ctrl+z--返回 key("ctrl+z",function () { api.ret(); }); //重做--- key("ctrl+shift+x",function () { api.again(); })
为此我们可以使用键盘的指定组合实现和鼠标点击一样的效果。
这里需要说明一下客户端的api中的id值,也是通过插件来动态生成的------插件名称为:uuid.js。这里附上源码
/* uuid.js - version 0.2 javascript class to create a uuid like identifier copyright (c) 2006-2008, erik giberti (af-design), all rights reserved. this program is free software; you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation; either version 2 of the license, or (at your option) any later version. this program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details. you should have received a copy of the gnu general public license along with this program; if not, write to the free software foundation, inc., 59 temple place, suite 330, boston, ma 02111-1307 usa the latest version of this file can be downloaded from http://www.af-design.com/resources/javascript_uuid.php history: 6/5/06 - initial release 5/22/08 - updated code to run faster, removed randrange(min,max) in favor of a simpler rand(max) function. reduced overhead by using gettime() method of date class (suggestion by james hall). known issues: - still no way to get mac address in javascript - research into other versions of uuid show promising possibilities (more research needed) - documentation needs improvement */ // on creation of a uuid object, set it's initial value function uuid(){ this.id = this.createuuid(); } // when asked what this object is, lie and return it's value uuid.prototype.valueof = function(){ return this.id; } uuid.prototype.tostring = function(){ return this.id; } // // instance specific methods // uuid.prototype.createuuid = function(){ // // loose interpretation of the specification dce 1.1: remote procedure call // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37 // since javascript doesn't allow access to internal systems, the last 48 bits // of the node section is made up using a series of random numbers (6 octets long). // var dg = new date(1582, 10, 15, 0, 0, 0, 0); var dc = new date(); var t = dc.gettime() - dg.gettime(); var h = '-'; var tl = uuid.getintegerbits(t,0,31); var tm = uuid.getintegerbits(t,32,47); var thv = uuid.getintegerbits(t,48,59) + '1'; // version 1, security version is 2 var csar = uuid.getintegerbits(uuid.rand(4095),0,7); var csl = uuid.getintegerbits(uuid.rand(4095),0,7); // since detection of anything about the machine/browser is far to buggy, // include some more random numbers here // if nic or an ip can be obtained reliably, that should be put in // here instead. var n = uuid.getintegerbits(uuid.rand(8191),0,7) + uuid.getintegerbits(uuid.rand(8191),8,15) + uuid.getintegerbits(uuid.rand(8191),0,7) + uuid.getintegerbits(uuid.rand(8191),8,15) + uuid.getintegerbits(uuid.rand(8191),0,15); // this last number is two octets long return tl + h + tm + h + thv + h + csar + csl + h + n; } // // general methods (not instance specific) // // pull out only certain bits from a very large integer, used to get the time // code information for the first part of a uuid. will return zero's if there // aren't enough bits to shift where it needs to. uuid.getintegerbits = function(val,start,end){ var base16 = uuid.returnbase(val,16); var quadarray = new array(); var quadstring = ''; var i = 0; for(i=0;i<base16.length;i++){ quadarray.push(base16.substring(i,i+1)); } for(i=math.floor(start/4);i<=math.floor(end/4);i++){ if(!quadarray[i] || quadarray[i] == '') quadstring += '0'; else quadstring += quadarray[i]; } return quadstring; } // numeric base conversion algorithm from irt.org // in base 16: 0=0, 5=5, 10=a, 15=f uuid.returnbase = function(number, base){ // // copyright 1996-2006 irt.org, all rights reserved. // // downloaded from: http://www.irt.org/script/146.htm // modified to work in this class by erik giberti var convert = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; if (number < base) var output = convert[number]; else { var msd = '' + math.floor(number / base); var lsd = number - msd*base; if (msd >= base) var output = this.returnbase(msd,base) + convert[lsd]; else var output = convert[msd] + convert[lsd]; } return output; } // pick a random number within a range of numbers // int b rand(int a); where 0 <= b <= a uuid.rand = function(max){ return math.floor(math.random() * max); } // end of uuid class file
更多关于javascript相关内容还可查看本站专题:《javascript面向对象入门教程》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》、《javascript遍历算法与技巧总结》及《javascript数学运算用法总结》
希望本文所述对大家javascript程序设计有所帮助。