zhangdizhangdi

组合模式 📖

定义

组合模式(Composite Pattern),将对象组合成树形结构,使“单个对象”和“组合对象”可以被一致对待。
不管是“一个节点”还是“一堆节点”,用法都一样。

实现

js
class Component {
  render() {}
}

class Leaf extends Component {
  render() {
    console.log('leaf')
  }
}

class Composite extends Component {
  constructor() {
    super()
    this.children = []
  }

  add(child) {
    this.children.push(child)
  }

  render() {
    this.children.forEach(child => child.render())
  }
}

const root = new Composite()
const child1 = new Leaf()
const child2 = new Composite()

child2.add(new Leaf())

root.add(child1)
root.add(child2)

root.render()

前端应用

1. React/Vue组件树

👉 ✔️ 统一 render
👉 ✔️ 树结构

js
<App>
  <Header />
  <Content>
    <Article />
  </Content>
</App>

2. DOM树

js
<div>
  <span></span>
</div>

node.appendChild()
node.remove()

3. 菜单

js
const menu = {
  name: '系统',
  children: [
    { name: '用户' },
    { name: '权限' }
  ]
}