js设计模式-组合模式
生活随笔
收集整理的這篇文章主要介紹了
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 }; View Code應用:
<!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>結果:
?
轉載于:https://www.cnblogs.com/tengri/p/5348073.html
總結
以上是生活随笔為你收集整理的js设计模式-组合模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 创建定时器
- 下一篇: Top 置顶小图标