js设计模式学习笔记(十):组合模式

组合模式

特点

  • 生成树形结构,表示 “ 整体-部分” 关系,但又模糊整体和部分的区别,因为 每一个部分的数据结构相同。
  • 让整体和部分都与具有一致的操作性,任意一个结点对象操作 API 是相同的
  • 整体和部分的数据结构都是一样的 _类似于 dom 对象,vnode 都是一种实现 _

介绍

  • 组合模式通过对象的多态性表现,使得用户对单个对象和组合对象的使用具有一致性

  • 明确提出的组合模式,实质是一种树的体现。由统一的根节点向下层出发,不断的查找属于自己的一系列方法与问题

  • 组合模式提供的是一种树形结构的搜索的方式,将多种操作进行合并,并允许多层嵌套

  • 组合模式常用场景

    • 问题具有明显的阶级层次,主分结构明确
    • 组合模式并不是主子结构,主子结构有明显的继承关系,主分结构只是主入口其他分支进行记录管理
    • 并不会限制分支结构的具体实现内容,主入口将问题委托到其他的分支部分。
  • 之所以组合模式能模糊组合对象和叶子对象,是因为组合对象和叶子对象均实现相同的对外接口,能够让模式对用户透明,但这也留下了隐患(见安全问题)

  • 组合模式最重要的是提供一种搜索方法,实现主分之间的互相映射关系,如下

demo

更多详细代码

  • 组合模式优化 详见 /demo/13_组合模式

function Command (){
    this.commandList = [];
}

Command.prototype.add = function(command){
    if(!command.add || !command.excute){
        throw new Error("command must have add() and excute()")
    }
    this.commandList.push(command);
}

Command.prototype.excute = function(){
    for(let command of this.commandList){
        command.excute();
    }
}

function MiscorCommand(excute){
    if(typeof excute !== "function"){
        throw new Error("excute mest be a function")
    }
    this.excute = excute;
}

MiscorCommand.prototype.add = function(){
    throw new Error("MiscorCommand couldn't add() ")
}

const command1 = new Command();
const command2 = new Command();
const mCommand1_1 = new MiscorCommand(function(){console.log("mCommand1_1")});
const mCommand1_2 = new MiscorCommand(function(){console.log("mCommand1_2")});
const mCommand2_1 = new MiscorCommand(function(){console.log("mCommand2_1")});
command.add(mCommand1_1);
command.add(mCommand1_2);
command.add(command2);
command2.add(mCommand2_1);

command.excute();
command2.excute();