将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
class VNode {
constructor(tag, attr) {
this.tag = tag
this.attr = attr
this.children = []
}
addChildren(children) {
this.children.push(children)
}
delChildren(children) {
const index = this.children.indexOf(children)
if(index != -1) this.children.splice(index, 1)
}
getChildren() {
return this.children
}
}
const div = new VNode('div', {id: 'root'})
const p1 = new VNode('p')
const p2 = new VNode('p')
div.addChildren(p1)
div.addChildren(p2)
p1.addChildren('123')
div.getChildren()
div.delChildren(p1)
div.getChildren()