组合模式

Compose

概述
在对象间构建树形结构
对基本对象和组合对象的操作没有区别,一致对待,如深度优先遍历
对象可以有很多层
类似递归操作
应用
文件扫描:遍历
侧边栏:根据用户的权限区别创建
多级菜单
扫描文件夹
创建
先创建根文件夹,再创建若干子文件夹
然后创建若干文件,并添加到不同的子文件夹
最后把子文件夹添加到根文件
扫描:从根文件夹开始扫描
Compose
const Folder = function (folder) {
  this.folder = folder
  this.lists = []
}

Folder.prototype.add = function (file) {
  this.lists.push(file)
}

Folder.prototype.scan = function () {
  console.log('scan folder', this.folder);
  this.lists.forEach(item => {
    item.scan()
  })
}

const File = function (file) {
  this.file = file
}

File.prototype.scan = function () {
  console.log('scan file ', this.file);
}

let rootFolder = new Folder('root')

let htmlFolder = new Folder('html')
let h0File = new File('h0')
let h1File = new File('h1')
let h2File = new File('h2')
htmlFolder.add(h0File)
htmlFolder.add(h1File)
htmlFolder.add(h2File)

let cssFolder = new Folder('css')
let c0File = new File('c0')
let c1File = new File('c1')
let c2File = new File('c2')
cssFolder.add(c0File)
cssFolder.add(c1File)
cssFolder.add(c2File)

let jsFolder = new Folder('js')
let j0File = new File('j0')
let j1File = new File('j1')
let j2File = new File('j2')
jsFolder.add(j0File)
jsFolder.add(j1File)
jsFolder.add(j2File)

rootFolder.add(htmlFolder)
rootFolder.add(cssFolder)
rootFolder.add(jsFolder)

rootFolder.scan()
多级菜单
1. 在Folder的scan中创建一级菜单
2. 在File的scan中创建二级菜单
DOM挂载点
<ul id="menu"></ul>
Usage
const Folder = function (folder) {
  this.folder = folder
  this.lists = []
}

Folder.prototype.add = function (file) {
  this.lists.push(file)
}

Folder.prototype.scan = function () {
  console.log('scan folder: ', this.folder);
  let oul = document.createElement('ul')
  if (this.folder === 'root') {
  } else {
    let oli = document.createElement('li')
    oli.innerHTML = this.folder
    oli.appendChild(oul)
    menu.appendChild(oli)
  }
  this.lists.forEach(item => {
    item.scan(oul)
  })
}

const File = function (file) {
  this.file = file
}

File.prototype.scan = function (ul) {
  console.log('scan file: ', this.file, ul);
  let li = document.createElement('li')
  li.innerHTML = this.file
  ul.appendChild(li)
}

let rootFolder = new Folder('root')
let htmlFolder = new Folder('html')
let cssFolder = new Folder('css')
let jsFolder = new Folder('js')

let h0File = new File('h0')
let h1File = new File('h1')
let h2File = new File('h2')
htmlFolder.add(h0File)
htmlFolder.add(h1File)
htmlFolder.add(h2File)

let c0File = new File('c0')
let c1File = new File('c1')
let c2File = new File('c2')
cssFolder.add(c0File)
cssFolder.add(c1File)
cssFolder.add(c2File)

let j0File = new File('j0')
let j1File = new File('j1')
let j2File = new File('j2')
jsFolder.add(j0File)
jsFolder.add(j1File)
jsFolder.add(j2File)

rootFolder.add(htmlFolder)
rootFolder.add(cssFolder)
rootFolder.add(jsFolder)

rootFolder.scan()