The template method pattern is defined as:
A skeleton or step of an algorithm is defined in a method, and some steps are delayed to subclasses for implementation. The template method allows subclasses to redefine some steps in the algorithm without changing the algorithm structure.
The template method defines an operation process sequence in the base class, which can ensure that the steps are carried out in sequence. Some specific implementations of some steps have been declared in the base class, and the specific implementations of some changing steps are handed over to the subclass to implement, thus delaying some steps into the subclass. One of the biggest benefits of the template method is that it can set a business process to be executed in a certain strict order, controlling the execution steps of the entire algorithm.
This method defines the algorithm into a set of steps, in which all steps that want the subclass to perform custom implementation are defined as abstract methods. The characteristic of abstract base classes is that the template method is generally set to final, which prevents the subclass from overwriting the steps of the algorithm, implementing some of the same operations or steps directly in the base class, and setting some of the changing steps to abstract and the subclass to complete.
Java implementation example
Class diagram:
/** * Business process template, providing the basic framework*/ public abstract class BaseTemplate { public abstract void part1(); public abstract void part2(); public abstract void part3(); //In order to strictly experimental results, final cannot be rewritten using final void useTemplateMethod() { part1(); part2(); part3(); } } /** * Template implementation method 1 */ public class TemplateMethod extends BaseTemplate { @Override public void part1() { System.out.println("Template method 1"); } @Override public void part2() { System.out.println("Template method 2"); } @Override public void part3() { System.out.println("Template method 3"); } } /** * Template implementation method 2 * @author stone * */ public class TemplateMethod2 extends BaseTemplate { @Override public void part1() { System.out.println("Template method 11"); } @Override public void part2() { System.out.println("Template method 22"); } @Override public void part3() { System.out.println("Template method 33"); } } public class Test { public static void main(String[] args) { BaseTemplate tm = new TemplateMethod(); tm.useTemplateMethod(); System.out.println(""); BaseTemplate tm2 = new TemplateMethod2(); tm2.useTemplateMethod(); } }Print:
Template method 1 Template method 2 Template method 3 Template method 11 Template method 22 Template method 33