The template method pattern defines a framework for the algorithm, which defines the method's execution steps, but each step is implemented by a specific subclass. This allows you to define specific steps for an algorithm without changing the entire algorithm structure.
The class structure of the template method pattern is as follows:
Template functions: A template method is defined in an abstract base class that specifies the structure of the entire algorithm and defines the execution steps of the method by invoking several other methods to implement the steps. The method is called to execute outside the class, so it is declared as a public type. At the same time, the method refuses to rewrite, so it is declared with final.
Step function: the whole algorithm is divided into several steps, and each step is implemented by a single step method. If the business of the step is clear, it can be implemented directly in the base class as a concrete method, because you do not want it to be called outside the class, it is declared as a private method, if it is not clear, you can declare the method as an abstract method, by inheriting its subclass to be replicated. To ensure that subclasses can replicate to it, declare it as protected (subclass permission) or default (in-Package permissions).
At this point, we are faced with a problem, if the algorithm to perform this series of steps, want to skip a step, what should be done? In this case you need to provide a so-called "hook method" in the template method, that is, before each step with the if judgment; the method provides a default implementation or is implemented by a specific subclass to control whether or not to skip a specific step, so declare it as protected or default.
Usage Scenarios
- The algorithm follows similar logic.
- When refactoring the code, extract the same code into the parent class.
- Important for complex algorithms, the algorithm core can use template algorithms.
Advantages
Good encapsulation, good reusability, shielding details, easy maintenance
Disadvantages
Because of the restriction of single inheritance, once a subclass inherits from another parent class, it cannot inherit the template base class.
Template method pattern of design pattern