Template Method Pattern

The Template Method Pattern defines the framework for executing certain algorithms. An abstract class publicly defines the way or template to execute its methods, and its subclasses can override methods as needed or call them in the way defined in the abstract class. This type of design pattern falls under the category of behavioral patterns.

Description

The Template Method Pattern is a behavioral design pattern used to define the framework of an algorithm in an operation, thus deferring some steps to subclasses, which can redefine certain steps of the algorithm without changing its structure.

Advantages

  • Encapsulates the invariant parts, extends the variable parts, and enhances extensibility.
  • Extracts common code, making it easier to maintain and increasing code reusability.
  • Behavior controlled by the parent class, implemented by the subclasses, achieves reverse control, conforms to the Open/Closed principle.

Disadvantages

  • Each different implementation requires a subclass to implement it, increasing the number of classes and making the system more complex.

Applicable Scenarios

  • Multiple subclasses sharing the same method with similar logic.
  • Important and complex methods that can be considered as template methods.

Implementation

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
})();

Daily Question

https://github.com/WindrunnerMax/EveryDay

References

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