This pattern defines the skeleton of an algorithm in a method, and leaves the details of the algorithm to be implemented by subclasses. This can be useful when you want to define the overall structure of an algorithm, and when you want to allow subclasses to customize the details of the algorithm.
Here is an example of the template method pattern in JavaScript:
}
}
}
}
}
}
}
}
}
subclass1.
// Output:
// Executing step 1...
// Executing custom step 2...
// Executing step 3...
subclass2.
// Output:
// Executing step 1...
// Executing step 2...
// Executing custom step 3...
The Template class defines the overall structure of an algorithm in the algorithm() method, and the step1(), step2(), and step3() methods represent the details of the algorithm that are left to be implemented by subclasses.
The Subclass1 and Subclass2 classes are subclasses of the Template class, and they override the step2() and step3() methods, respectively, to provide custom implementations of these steps.
To use the template method pattern, we create instances of the Subclass1 and Subclass2 classes, and then call the algorithm() method on these instances. The algorithm() method of the Template class defines the overall structure of the algorithm, and the overridden methods of the subclasses provide the custom implementations of the details of the algorithm.