組合模式
組合模式(Composite Pattern),又叫部分整體模式,是用于把一組相似的對象當(dāng)作一個單一的對象。組合模式依據(jù)樹形結(jié)構(gòu)來組合對象绞愚,用來表示部分以及整體層次。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式颖医,它創(chuàng)建了對象組的樹形結(jié)構(gòu)位衩。
特征
- 層層嵌套的樹狀結(jié)構(gòu),整體由復(fù)合物-葉子兩類元素組成熔萧。
- 復(fù)合物和葉子有相同的接口糖驴,不同的實現(xiàn)
//composite
class Container {
constructor(id) {
this.children = []
this.element = document.createElement('div')
this.element.id = id
this.element.style.border = '1px solid black'
this.element.style.margin = '10px'
this.element.classList.add('container')
}
add(child) {
this.children.push(child)
this.element.appendChild(child.getElement())
}
hide() {
this.children.forEach(node => node.hide())
this.element.style.display = 'none'
}
show() {
this.children.forEach(node => node.show())
this.element.style.display = ''
}
getElement() {
return this.element
}
}
// leaf
class Text {
constructor(text) {
this.element = document.createElement('p')
this.element.innerText = text
}
add() {}
hide() {
this.element.style.display = 'none'
}
show() {
this.element.style.display = ''
}
getElement() {
return this.element
}
}
// 建立 header 節(jié)點
let header = new Container('header')
// 建立兩個葉節(jié)點
header.add(new Text('標(biāo)題'))
header.add(new Text('logo'))
let main = new Container('main')
main.add(new Text('這是內(nèi)容1'))
main.add(new Text('這是內(nèi)容2'))
let page = new Container('page')
page.add(header)
page.add(main)
page.show()
document.body.appendChild(page.getElement())
image.png