JS设计模式---8.组合模式

组合模式是什么

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

组合模式之利

  • 耦合低,利于重构
  • 减少代码量
  • 节点自由度高

组合模式之弊

  • 层次较大时,性能会受到影响

组合对象的结构

组合对象

如上图所示,组合对象的层次体系中有两种类型的对象:叶对象和组合对象。一个组合对象由别的组合对象和叶对象组成,而叶对象不再有子对象。
叶对象是组合对象的基本元素,也是各种操作的落实地点。

适用场合

  • 存在一批组织成某种层次体系的对象(具体的结构再开发期间无法得知)
  • 希望对这批对象或其中的一部分对象实施一个操作

一个栗子

假设你的任务是创建一个图片库。我们希望能构有选择的隐藏或显示图片库的特定功能。这可能是单独的图片,也可能是图片库。

   // 首先我们创建图片库类  也就是组合对象
    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)

运行后我们的页面结构为


html

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容