天天看點

模闆方法模式

模闆方法模式

Template Method Pattern

定義了如何執行某些算法的架構,一個抽象類公開定義了執行它的方法的方式或模闆,其子類可以按需要重寫方法實作,也可以調用将以抽象類中定義的方式進行,這種類型的設計模式屬于行為型模式。

描述

模闆方法模式是一種行為設計模式,用于定義操作中算法的程式架構,進而将某些步驟推遲到子類中,其可以重新定義算法的某些步驟,而無需更改算法的結構。

優點

  • 封裝不變部分,擴充可變部分,提高了拓展性。
  • 提取公共代碼,便于維護,提高代碼複用性。
  • 行為由父類控制,子類實作,實作了反向控制 ,符合開閉原則。

缺點

  • 每一個不同的實作都需要一個子類來實作,導緻類的個數增加,使得系統更加龐大。

适用環境

  • 有多個子類共有的方法,且邏輯相同。
  • 重要的、複雜的方法,可以考慮作為模闆方法。

實作

class Builder {
    build() {
        this.start();
        this.lint();
        this.assemble();
        this.deploy();
    }
}

class AndroidBuilder extends Builder {
    constructor(){
        super();
    }
    start() {
        console.log("Ready to start build android");
    }
    
    lint() {
        console.log("Linting the android code");
    }
    
    assemble() {
        console.log("Assembling the android build");
    }
    
    deploy() {
        console.log("Deploying android build to server");
    }
}

class IosBuilder extends Builder {
    constructor(){
        super();
    }
    start() {
        console.log("Ready to start build ios");
    }
    
    lint() {
        console.log("Linting the ios code");
    }
    
    assemble() {
        console.log("Assembling the ios build");
    }
    
    deploy() {
        console.log("Deploying ios build to server");
    }
}

(function(){
    const androidBuilder = new AndroidBuilder();
    androidBuilder.build();
    // Ready to start build android
    // Linting the android code
    // Assembling the android build
    // Deploying android build to server

    const iosBuilder = new IosBuilder();
    iosBuilder.build();
    // Ready to start build ios
    // Linting the ios code
    // Assembling the ios build
    // Deploying ios build to server
})();
           

每日一題

https://github.com/WindrunnerMax/EveryDay
           

參考

https://juejin.im/post/6844903615476269064
https://www.runoob.com/design-pattern/template-pattern.html
https://github.com/sohamkamani/javascript-design-patterns-for-humans#-template-method