# 模板方法模式 模板方法模式`Template Method Pattern`定义了如何执行某些算法的框架,一个抽象类公开定义了执行它的方法的方式或模板,其子类可以按需要重写方法实现,也可以调用将以抽象类中定义的方式进行,这种类型的设计模式属于行为型模式。 ## 概述 模板方法模式是一种行为设计模式,用于定义操作中算法的程序框架,从而将某些步骤推迟到子类中,其可以重新定义算法的某些步骤,而无需更改算法的结构。 ### 优点 * 封装不变部分,扩展可变部分,提高了拓展性。 * 提取公共代码,便于维护,提高代码复用性。 * 行为由父类控制,子类实现,实现了反向控制 ,符合开闭原则。 ### 缺点 * 每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。 ### 适用环境 * 有多个子类共有的方法,且逻辑相同。 * 重要的、复杂的方法,可以考虑作为模板方法。 ## 实现 ```javascript 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 ```