js設(shè)計(jì)模式-組合模式

組合模式
組合模式(Composite Pattern),又叫部分整體模式,是用于把一組相似的對象當(dāng)作一個(gè)單一的對象。組合模式依據(jù)樹形結(jié)構(gòu)來組合對象,用來表示部分以及整體層次。這種類型的設(shè)計(jì)模式屬于結(jié)構(gòu)型模式,它創(chuàng)建了對象組的樹形結(jié)構(gòu)。


特征

  • 層層嵌套的樹狀結(jié)構(gòu),整體由復(fù)合物-葉子兩類元素組成。
  • 復(fù)合物和葉子有相同的接口,不同的實(shí)現(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é)點(diǎn)
let header = new Container('header')

// 建立兩個(gè)葉節(jié)點(diǎn)
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容