The template approach pattern is a design pattern that encapsulates changes to improve system extensibility.

In traditional object-oriented languages, in a program that uses the template method pattern, the class of methods and execution order of the subclass are unchanged, so we abstract this logic into the template method of the parent class. However, how the methods of subclasses are implemented is variable, so we encapsulate this part of the changing logic in the subclass. By adding new subclasses, we can add new functionality to the system without changing the abstract superclass and other subclasses, which is open and closed.

Application scenarios

Let’s say we have some parallel subclasses, some of the same behaviors, some of the different behaviors. If the same and different behaviors are mixed in the implementation of each subclass, it means that the same behaviors are repeated in each subclass. But in fact, the same behavior can be moved to another single place, and the template method pattern was created to solve this problem. In the template method pattern, the same parts of the subclass implementation are moved up into the parent class, leaving the different parts to be implemented by the subclass. This is also a good example of the idea of generalization.

composition

The template method pattern consists of two parts:

  • Abstract superclass: An algorithm framework that usually encapsulates a subclass in an abstract superclass, including the implementation of some common methods and the execution of all methods in the subclass (such as execution order, conditional execution, etc.).
  • Concrete implementation subclasses: By inheriting this abstract class, subclasses also inherit the entire algorithm structure and can choose to override the methods of the parent class.

The sample

The template method pattern is usually implemented through inheritance, which is not often used in JavaScript development. Most of the time, we prefer mix-in methods to extend attributes to objects.

Abstract classes define how methods are executed (such as order of execution, conditional execution, etc.), and their subclasses can override the methods being executed as needed. The core is abstract classes.

class Tax {
  calc(value) {
    if (value >= 1000)
      value = this.overThousand(value);

    return this.complementaryFee(value);
  }
  complementaryFee(value) {
    return value + 10; }}class Tax1 extends Tax {
  constructor() {
    super(a); }overThousand(value) {
    return value * 1.1; }}Copy the code

reference

JavaScript design patterns and development practices