1. 程式人生 > 其它 >js 設計模式——建造者模式

js 設計模式——建造者模式

定義

將一個複雜物件的構建與它的例項分離,使得同樣的構建過程可以建立不同的例項。

建造者模式實現

比如你打算裝修一個房子,首先你會找到開發商提出你的需求

/**
  * @information: 業主
  */
  class Owner {
    constructor (need){
      this.need = need || [];
    }

    getNeed() {
      return this.need;
    }
  }

然後開發商會根據你的需求去找設計師設計圖紙

  /**
  * @information: 開發商
  */
  class Developer {
    constructor(need) {
      
this.need = need || []; console.log("我需要這樣的房間:"+need); } construct() { console.log("開始建造"); let workerOk = this.need.map(el => { let builder = new CreatDiagram(); builder.build(el); return builder.getResult(); }); console.log("房子不錯"); console.log(workerOk); } }
/** * @information: 設計圖抽象類 */ class Diagram { constructor(){ console.log("拿到圖紙"); } build (partName){ console.log(`觀察${partName}圖紙`); } }

拿到圖紙之後,再招工人

  /**
  * @information: 工人類
  */
  class Worker {
    constructor (material) {
      console.log(`我建造了${material}`);
      
this.data = material; } } /** * @information: 設計圖實現 */ class CreatDiagram extends Diagram { constructor() { super(); } build (partName) { super.build(partName); console.log(`建造開始${partName}`); this.worker = new Worker(partName); } getResult() { console.log("完工"); return this.worker; } }

最後就開始裝修了

let owner = new Owner(['臥室', '廚房', '客廳']);
let home = new Developer(owner.getNeed());
home.construct();

具體列印結果如下

建造者模式的優缺點

優點

  • 在建造者模式裡,不需要知道建造的過程是怎麼樣的,建立的例項會與過程解耦。
  • 建造者模式裡可以根據不同的具體實現來得到不同的例項。
  • 每個具體的建造類都相對獨立,方便替換和新增。

缺點

  • 如果類內部的差異比較大,或者變化複雜的話,會增加很多對應的實現類,使得程式碼比較臃腫。

總結

建造者模式返回的是各種類組裝好的一個物件,各有各的應用場景,建造者模式可以比較適用那些有固定生成順序的物件。