23 design patterns, Chapter 12: Java template method mode
Definition: Defines the framework of an algorithm in an operation, and delays some steps to a subclass, so that the subclass can redefine certain specific steps in the algorithm without changing the structure of the algorithm.
Type: Behavioral Pattern
Class diagram:
In fact, the template method is a frequently used pattern in programming. Let’s first look at an example. One day, programmer A got a task: give 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, so sorting is a bit troublesome. But A has a way, first complete the printing function and find someone else to do the sort function.
abstract class AbstractSort { /** * Sort 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 writing, A found a colleague who had just graduated and started working and said: There is a task, I have written the main logic, so you can implement the remaining logic. So I gave the AbstractSort class to B and let B write to implement it. B took it over and saw it. It was too simple. It was 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; // Min value variable int indexMin = 0; // Min value index variable int Temp; // Staging variable for (int i = index; i < array.length; i++) { if (array[i] < MinValue){ // Find the minimum value MinValue = array[i]; //Storage the minimum value indexMin = i; } } Temp = array[index]; //Swap two numeric values array[index] = array[indexMin]; array[indexMin] = Temp; } }After writing it, give it to A, and A will take it to run it:
public class Client { public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // Preset data array public static void main(String[] args){ AbstractSort s = new ConcreteSort(); s.showSortResult(a); } } Running results:
Sort results: 0 1 3 4 5 7 9 10 12 32
It runs normally. OK, the task is completed. That's right, this is the template method pattern. Most graduates who have just entered the workplace should have experiences similar to B. A complex task is written by the great people in the company, and then write the simpler methods into abstraction and hand them over to other colleagues to develop. This division of labor is often used in companies with relatively obvious levels of programmers. For example, if a project team has architects, senior engineers, and junior engineers, the architects generally use a large number of interfaces and abstract classes to string together the logic of the entire system, and the implementation coding is handed over to senior engineers and junior engineers according to the difficulty. How about it, have you used the template method mode?
Structure of template method pattern
The template method pattern consists of an abstract class and a (or a group of) implementation classes through inheritance structures. The methods in abstract classes are divided into three types:
Abstract method: The parent class only declares but does not implement it, but defines the specifications, and then implements them by its subclass.
Template method: declared and implemented by abstract classes. Generally speaking, template methods call abstract methods to complete the main logical functions, and template methods are mostly defined as final types, indicating that the main logical functions cannot be rewritten in subclasses.
Hook method: declared and implemented by abstract class. However, 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 whether the program is stable.
Implementation classes are used to implement details. The template method in abstract classes completes business logic by implementing class extension methods. As long as the extension method in the implementation class passes unit test, the overall function will generally not have major errors under the premise that the template method is correct.
Advantages and applicable scenarios of template method
Easy to expand. Generally speaking, the template method in an abstract class is a part that is not easy to reversely change, while the abstract method is a part that is easy to reversely change. Therefore, by adding the implementation class, it is generally easy to expand the function, which conforms to the principle of opening and closing.
Easy to maintain. For the template method mode, it is precisely because their main logic is the same that the template method is used. If the template method is not used, it is very inconvenient to maintain the same code in a mess.
More flexible. Because there are hook methods, the implementation of subclasses can also affect the operation of the main logic in the parent class. However, while being flexible, because subclasses affect the parent class, violating the Richter replacement principle will also bring risks to the program. This puts higher requirements on the design of abstract classes.
When multiple subclasses have the same method and the methods are logically the same, you can consider using the template method pattern. This mode is also suitable for using the program when the main framework of the program is the same and the details are different.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.