组合模式是什么
组合模式又叫整体模式。它把一批子对象组织为树形结构,只要一条命令就可以操作树中的所有对象
组合模式之利
组合模式之弊
组合对象的结构

如上图所示,组合对象的层次体系中有两种类型的对象:叶对象和组合对象。一个组合对象由别的组合对象和叶对象组成,而叶对象不再有子对象。
叶对象是组合对象的基本元素,也是各种操作的落实地点。
适用场合
- 存在一批组织成某种层次体系的对象(具体的结构再开发期间无法得知)
- 希望对这批对象或其中的一部分对象实施一个操作
一个栗子
假设你的任务是创建一个图片库。我们希望能构有选择的隐藏或显示图片库的特定功能。这可能是单独的图片,也可能是图片库。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| var DynamicGallery = function (id) { this.children = []; this.element = document.createElement('div'); this.element.id = id; this.element.className = 'dynamic-gallery'; } DynamicGallery.prototype = { add:function(child){ this.children.push(child); this.element.appendChild(child.getElement()) }, remove:function (child) { for (let node, i = 0; node = this.getChild(i); i++) { if (node == child) { this.children.splice(i,1); break; } } this.element.removeChild(child.getElement()); }, getChild:function (i) { return this.children[i]; }, hide:function(){ for (let node,i = 0; node = this.getChild(i); i++) { node.hide(); } this.element.style.display = 'none'; }, show:function(){ this.element.style.display = 'block'; for (let node,i = 0; node = this.getChild(i); i++) { node.show(); } }, getElement:function(){ return this.element; } } var GalleryImage = function (src) { this.element = document.createElement('img'); this.element.className = 'gallery-image'; this.element.src = src; }
GalleryImage.prototype = { add:function(){}, remove:function(){}, getChild:function(){}, hide:function(){ this.element.style.display = 'none' }, show(){ this.element.style.display = '' }, getElement:function(){ return this.element; } } var topGallery = new DynamicGallery('top-gallery'); var a = new GalleryImage('./01.png') topGallery.add(a) document.body.appendChild(topGallery.element)
|
运行后我们的页面结构为

显示和隐藏也是没有问题的。