Basic introduction

  1. A Template Method Pattern, also known as a Template Pattern, exposes a Template in an abstract class that defines the methods that execute it. Its subclasses can override method implementations as needed, but the calls will be made in the manner defined in the abstract class.
  2. Simply put, the template method pattern defines the skeleton of an algorithm in an operation, while deferring some steps to subclasses so that subclasses can redefine specific steps of an algorithm without changing the structure of that algorithm.
  3. This type of design pattern is behavioral.

  1. AbstractClass AbstractClass implements template methods and defines the skeleton of the algorithm. Concrete subclasses are required to implement other abstract methods operationr2,3,4
  2. ConcreteClass implements the abstract method operationr2,3,4 to complete the characteristic subclass steps in the algorithm

The hook method of the template method pattern

In the parent class of the template method pattern, we can define a method that does nothing by default and subclasses can override it as they wish, called a “hook.”

The code analysis

Warehouse address :gitee.com/y2m/java-de… TemplateMethod folder

Applications in Spring

The template method pattern used when the Spring IOC container is initialized

Notes and details

  1. The basic idea is that the algorithm only exists in one place, in the parent class, and is easy to modify. When an algorithm needs to be modified, it simply changes the parent’s template methods or some steps that have already been implemented, and subclasses inherit those changes to maximize code reuse. The template methods and some of the implemented steps of the parent class are inherited and used directly by subclasses.
  2. It not only unified the algorithm, but also provided great flexibility. The template method of the parent class ensures that the structure of the algorithm remains unchanged, while the subclass provides partial implementation of the steps.
  3. The disadvantage of this pattern is that each different implementation requires a subclass implementation, resulting in an increase in the number of classes, making the system larger. In general, template methods add the final keyword to prevent subclasses from overwriting template methods.
  4. The template method pattern usage scenario: When a process is to be completed, the process performs a series of steps, the series of steps are basically the same, but the individual steps may be different when implemented, and the template method pattern is usually considered to handle