组合模式介绍

组合模式:把多个对象组成树状结构来表示局部与整体,使得用户可以同时操作单个对象和对象的组合。

  • 可以以相同的方法处理对象的集合与其中的特定子对象。组合对象与组成该对象的对象可实现同一批的操作,对组合对象执行的操作会向下传递到所有的组成对象,使得所有组成对象都会执行同样的操作。
  • 可以将对象组织成树状结构,并且使整棵树可被遍历,所有组合对象都实现一个用来获取其子对象的方法,借助该方法可以隐藏实现的细节,组织子对象,使子对象内部的实现不形成依赖

对于创建动态用户界面来说,组合模式可以算是为其量身定做的,因为HTML结构正好符合组合模式适用场景的结构。

  • 存在一批组织成某种层次体系的对象
  • 希望对这批对象或者其中某一部分对象实施一个操作

组合模式擅长对大批量对象进行操作,转为组织这类对象把操作从一个层次向下一个层次传递设计,借此可以弱化对象间的耦合关系并且可以互换使用一些类或者实例,使代码模块化程度更高,维护更容易。

function ImagesStore( id ){
    this.children = [];
    this.element = document.createElement("div");
    this.element.id = id;
    this.element.className = "imgs-store";
    document.body.appendChild(this.element)
}
ImagesStore.prototype = {
    constructor : ImagesStore,
    add:function( child ){
        this.children.push( child );
        this.element.appendChild( child.getElement() );
    },
    remove:function( child ){
        for( var 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];
    },
    show:function(){
        this.element.style.display = '';
        for( var node, i=0; node = this.getChild(i); i++ ){
            node.show();
        }
    },
    hide:function(){
        for( var node, i=0; node = this.getChild(i); i++ ){
            node.hide();
        }
        this.element.style.display = 'none';
    },
    getElement:function(){
        return this.element;
    }
}
    //上面的组合对象中我们可以看出,原型上的hide和show方法不单单是对于当前element进行处理,还延伸到其包含的每一个叶对象上执行。这边就体现了组合模式的运行机制,一条命令在多个对象上激发复杂的或者递归的行为。


function ImageItem( src ){
    this.element = document.createElement("img");
    this.element.src = src;
    this.element.className = "img-item";
}
ImageItem.prototype = {
    constructor:ImageItem,
    add:function( child ){
        console.log("this is image object, no add function");
    },
    remove:function( child ){
        console.log("this is image object, no remove function");
    },
    getChild:function( i ){
        console.log("this is image object, no getChild function");
    },
    show:function(){
        this.element.style.display = '';
    },
    hide:function(){
        this.element.style.display = 'none';
    },
    getElement:function(){
        return this.element;
    }
}

使用组合模式组织起来的对象具有出色的层次结构,每当对顶层组合对象执行一个操作的时候,实际上是在对整个结构进行深度优先的节点搜索。但是这些优点都是用操作的代价换取的,比如每次顶级执行一次show方法,实际的操作就是整个树形结构的节点都会被遍历一次。但是组合对象的每个对象之间的耦合非常松散,可以简单的操作处理复杂的结果。

简单的说,组合模式是讲一批子对象组织为树形结构,一条顶层的命令会在操作树中所有的对象。提高了代码的模块化程度,对于动态的HTML界面具有很强的适用性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值