The template method pattern of Java design pattern defines the framework of an operating algorithm and defers some steps to subclasses, so that subclasses can redefine certain specific steps in the algorithm without changing the structure of the algorithm. Behavioral model
As shown below:
In fact, the template method is a frequently used pattern in programming. Let’s look at an example first. One day, programmer A got a task: given an array of integers, sort the numbers in the array from small to large, and then print out the sorted results. After analysis, this task can be roughly divided into two parts, sorting and printing. The printing function is easy to implement, but sorting is a bit troublesome. But A has a way to complete the printing function first and find someone else to do the sorting function.
abstract class AbstractSort { /** * Sort the array array from small to large * @param array */ protected abstract void sort(int[] array); public void showSortResult(int[] array){ this.sort(array); System.out.print("Sort result: "); for (int i = 0; i < array.length; i++){ System.out.printf("%3s", array[i]); } }}
After finishing writing, A found his colleague B who had just graduated and joined the job recently and said: There is a task. I have already written the main logic. You can implement the rest of the logic. So I gave the AbstractSort class to B and asked B to write the implementation. B took it over and took a look. It was too simple. It could be done in 10 minutes. The code is as follows:
class ConcreteSort extends AbstractSort { @Override protected void sort(int[] array){ for(int i=0; i<array.length-1; i++){ selectSort(array, i); } } private void selectSort(int[ ] array, int index) { int MinValue = 32767; // Minimum value variable int indexMin = 0; // Minimum value index variable int Temp; // Temporary storage variable for (int i = index; i < array.length; i++) { if (array[i] < MinValue){ // Find the minimum value MinValue = array[i]; // Store the minimum value indexMin = i; } } Temp = array[index] ; // Exchange two values array[index] = array[indexMin]; array[indexMin] = Temp; }}
After writing it, hand it to A, and A will run it:
public class Client { public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // Default data array public static void main(String[] args){ AbstractSort s = new ConcreteSort(); s.showSortResult(a); }}
Running results:
Sorting results: 0 1 3 4 5 7 9 10 12 32
It works fine. Okay, mission accomplished. Yes, this is the template method pattern. Most graduates who have just entered the workplace should have an experience similar to B. For a complex task, the best people in the company will write the main logic, and then write the seemingly simple methods into abstract ones, and leave them to other colleagues to develop. This division of labor is often used in companies with obvious levels of programming staff. For example, if a project team has an architect, senior engineer, and junior engineer, the architect will generally use a large number of interfaces and abstract classes to string together the logic of the entire system, and the implementation coding will be handed over to the senior engineer and junior engineer respectively according to the difficulty. Engineers do it. How about it, have you ever used the template method pattern?
The structure of the template method pattern:
The template method pattern consists of an abstract class and one (or a group of) implementation classes through an inheritance structure. The methods in the abstract class are divided into three types:
1. Abstract method : It is only declared in the parent class but not implemented. Instead, the specification is defined and then implemented by its subclasses.
2. Template method : declared and implemented by an abstract class. Generally speaking, template methods call abstract methods to complete main logical functions, and most template methods are defined as final types, indicating that the main logical functions cannot be overridden in subclasses.
3. Hook method : declared and implemented by the abstract class. But subclasses can be extended, and subclasses can affect the logic of template methods by extending hook methods.
The task of abstract classes is to build a logical framework, which is usually written by experienced personnel, because the quality of abstract classes directly determines the stability of the program.
Implementation classes are used to implement details. The template method in the abstract class completes the business logic by implementing the method of class extension. As long as the extension method in the implementation class passes the unit test and the template method is correct, there will generally be no major errors in the overall function.
Advantages and applicable scenarios of the template method:
Easy to expand. Generally speaking, the template method in an abstract class is the part that is not easy to change retroactively, while the abstract method is the part that is easy to change retroactively. Therefore, by adding implementation classes, it is generally easy to expand the function, which is in line with the opening and closing principle.
Easy to maintain. For the template method pattern, it is precisely because their main logic is the same that the template method is used. If the template method is not used, the same code is allowed to be scattered in different classes, which is very inconvenient to maintain. .
More flexible. Because of the hook method, the implementation of the subclass can also affect the operation of the main logic in the parent class. However, while being flexible, because the subclass affects the parent class, it violates the Liskov substitution principle and also brings risks to the program. This places higher requirements on the design of abstract classes.
When multiple subclasses have the same method and the logic of these methods is the same, you can consider using the template method pattern. This mode is also more suitable for situations where the main framework of the program is the same but the details are different.