javascript-组合模式

11次阅读

共计 1684 个字符,预计需要花费 5 分钟才能阅读完成。

组合模式

**// 组合模式在对象间形成树形结构
// 组合模式中基本对象和组合对象被一致对待
// 无须关心对象有多少层 调用时只需要在根部进行调用 **
结合了命令模式和组合模式的具体实现:

    const MacroCommand = function () {
      return {lists: [],
        add: function (task) {this.lists.push(task)
        },
        excute: function () { // 组合对象调用这里的 excute
          for (let i = 0; i < this.lists.length; i++) {this.lists[i].excute()}
        }
      }
    }
    const command1 = MacroCommand() // 基本对象
    command1.add({excute: () => console.log('煮咖啡') // 基本对象调用这里的 excute
    })
    const command2 = MacroCommand()
    command2.add({excute: () => console.log('打开电视')
    })
    command2.add({excute: () => console.log('打开音响')
    })
    const command3 = MacroCommand()
    command3.add({excute: () => console.log('打开空调')
    })
    command3.add({excute: () => console.log('打开电脑')
    })
    console.log(command1.lists) // 所对应的内存地址不一样
    console.log(command2.lists) // 所以 lists 保存的不一样
    console.log(command3.lists)

    const macroCommand = MacroCommand()
    macroCommand.add(command2) // 分次放入不同的参数
    macroCommand.add(command3) // 函数的引用不变,对应的就是同 
                                 // 一个堆
     macroCommand.add(command1)
     // 最后把 command1、2、3 都放入数组中 调用 excute, 触发每一个数 
      // 组中的 excute 方法
    macroCommand.excute()

demo2 —— 扫描文件夹
扫描文件夹时, 文件夹下面可以为另一个文件夹也可以为文件, 我们希望统一对待这些文件夹和文件, 这种情形适合使用组合模式。

   const Folder = function(folder){
    this.folder = folder
    this.lists = []}
   Folder.prototype.add = function(resource){this.lists.push(resource)
   }
   Folder.prototype.scan = function(){console.log('开始扫描文件夹',this.folder)
     for(let i =0,folder; folder = this.lists[i++];){folder.scan()
     }
   }
   const File = function(file){this.file = file}
   File.prototype.add = function(){throw Error('文件下不能添加其他文件夹或文件')
   }
   File.prototype.scan = function(){console.log('开始扫描文件',this.file)
   }
   const folder = new Folder('根文件加')
   const folder1 = new Folder('JS')
   const folder2 = new Folder('life')
   const file1 = new File('js 技术栈')
   const file2 = new File('权威')
   const file3 = new File('小王子')
   folder1.add(file1)
   folder1.add(file2)
   folder2.add(file3)
   folder.add(folder1)
   folder.add(folder2)
   folder.scan()

正文完
 0