JavaScript组合设计模式--改进引入案例分析
本文实例讲述了JavaScript组合设计模式--改进引入案例。分享给大家供大家参考,具体如下:
对于组合设计模式:
(1)组合模式中把对象分为两种(组合对象,和叶子对象)
(2)组合对象和叶子对象实现:同一批操作
(3)对组合对象执行的操作可以向下传递到叶子节点进行操作
(4)这样就会弱化类与类之间的耦合
(5)他常用的手法是把对象组合成属性结构的对象
根据组合模式的这些特性我们改写代码如下:
由于用到了接口检验所以我们先引入接口文件代码
//定义一个静态方法来实现接口与实现类的直接检验 //静态方法不要写出Interface.prototype,因为这是写到接口的原型链上的 //我们要把静态的函数直接写到类层次上 //定义一个接口类 varInterface=function(name,methods){//name:接口名字 if(arguments.length<2){ alert("必须是两个参数") } this.name=name; this.methods=[];//定义一个空数组装载函数名 for(vari=0;i(1)统一接口
varcomposite=newInterface("composite",["getChildByName","add"]);//侧重点获取子 varstudent=newInterface("composite",["goToClass","finishClass"]);//侧重点为每个对象的实现(2)定义组合类
varcompositeObj=function(name){ this.name=name; this.type="com";//默认是组合类 varchilds=newArray(); //得到相关的所有孩子节点 this.getChildByName=function(name){ //涉及到递归 vartoChilds=newArray(); if(!name){ for(vari=0;i(3)定义叶子类
varstudentObj=function(name){ this.name=name; this.type="student";//默认是叶子 //得到所有孩子节点 this.getChildByName=function(name){ if(this.name==name){ returnthis; }else{ returnnull; } } //增加子节点 this.add=function(child){ thrownewError("add不成被初始化(在叶子了中)") } //去上课 this.goToClass=function(name){ document.write(this.name+"去上课
"); } //下课 this.finishClass=function(name){ document.write(this.name+"下课
"); } Interface.ensureImplement(this,composite,student); }(4)应用---将学校,班级,组,学生关联起来
varastudent=newstudentObj("我是a同学"); varbstudent=newstudentObj("我是b同学"); varcstudent=newstudentObj("我是c同学"); vardstudent=newstudentObj("我是d同学"); varestudent=newstudentObj("我是e同学"); varfstudent=newstudentObj("我是f同学"); vargstudent=newstudentObj("我是g同学"); varhstudent=newstudentObj("我是h同学"); varistudent=newstudentObj("我是i同学"); varone=newcompositeObj("一班"); varoneOne=newcompositeObj("一班一组"); oneOne.add(astudent).add(bstudent); varoneTwo=newcompositeObj("一班二组"); oneTwo.add(cstudent).add(dstudent); one.add(oneOne).add(oneTwo); vartwo=newcompositeObj("二班"); vartwoOne=newcompositeObj("二班一组"); twoOne.add(estudent).add(fstudent); vartwoTwo=newcompositeObj("二班二组"); twoTwo.add(gstudent).add(hstudent).add(istudent) two.add(twoOne).add(twoTwo); varusPcat=newcompositeObj("组合设计模式培训学校"); usPcat.add(one).add(two);(5)客户端调用API,只需要简单的安排去上课即可,也就是客户端只需要写去上课的代码即可
usPcat.goToClass(); document.write("-------------------------
"); usPcat.goToClass("一班"); document.write("-------------------------
"); usPcat.goToClass("二班一组");感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码运行效果。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。