js设计模式-组合模式
组合模式是一种专为创建web上的动态用户界面而量身定制的模式。使用这种模式,可以用一条命令在多个对象上激发复杂的或递归的行为。这可以简化粘合性代码,使其更容易维护,而那些复杂行为则被委托给各个对象。
组合模式实例:图片库
1 /** 2 * 图片库 3 */ 4 var Composite = new Interface("Composite",["add","remove","getChild"]); 5 var GalleryItem = new Interface("GalleryItem",["hide","show"]); 6 7 //DynamicGallery class 8 9 var DynamicGallery = function(id){ 10 this.children = []; 11 12 this.element = document.createElement("div"); 13 this.element.id = id; 14 this.element.className = "dynamic-gallery"; 15 } 16 17 DynamicGallery.prototype = { 18 add:function(child){ 19 Interface.ensureImplements(child,Composite,GalleryItem); 20 this.children.push(child); 21 this.element.appendChild(child.getElement()); 22 }, 23 remove:function(child){ 24 for(var i =0, node; node = this.getChild(i);i++){ 25 if(node == child){ 26 this.children.splice(i,1); 27 break; 28 } 29 } 30 this.element.removeChild(child.getElement()); 31 }, 32 getChild:function(i){ 33 return this.children[i]; 34 }, 35 // Implemetn the GalleryItem interface 36 hide:function(){ 37 for(var node, i =0; node = this.getChild(i);i++){ 38 node.hide(); 39 } 40 this.element.style.display = "none"; 41 }, 42 show:function(){ 43 this.element.style.display = "block"; 44 for(var node, i =0; node = this.getChild(i);i++){ 45 node.show(); 46 } 47 }, 48 getElement:function(){ 49 return this.element ; 50 } 51 } 52 53 //GalleryImage class. 54 55 var GalleryImage = function(src){ 56 this.element = document.createElement("img"); 57 this.element.className = "gallery-image"; 58 this.element.src =src; 59 } 60 61 GalleryImage.prototype = { 62 add:function(){}, 63 remove:function(){}, 64 getChild:function(){}, 65 hide:function(){ 66 this.element.style.display = "none"; 67 }, 68 show:function(){ 69 this.element.style.display = ""; 70 }, 71 72 getElement:function(){ 73 return this.element; 74 } 75 };
应用:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="img"></div> </body> </html> <script type="text/javascript" src="Interface.js"></script> <script type="text/javascript" src="ImageLibs.js"></script> <script type="text/javascript"> var topGallery = new DynamicGallery("top-gallery"); topGallery.add(new GalleryImage("../img/dog/0.jpg")); topGallery.add(new GalleryImage("../img/dog/1.jpg")); topGallery.add(new GalleryImage("..//img/dog/2.jpg")); topGallery.add(new GalleryImage("../img/dog/3.jpg")); var vacationPhotos = new DynamicGallery("vacation-photos"); for(var i = 0 ; i< 5;i++){ vacationPhotos.add(new GalleryImage("../img/photo/" + i + ".jpg")); } topGallery.add(vacationPhotos); topGallery.show(); // vacationPhotos.hide(); console.log(topGallery); document.getElementById("img").appendChild(topGallery.element); topGallery.getChild(2).element.style.border = "2px solid red"; </script>
结果: