This article mainly introduces the template method pattern of design patterns. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
Definition:Define the framework of an algorithm in operation, and defer some steps to subclasses so that subclasses can not change the structure of the algorithm. That is, some specific steps in the algorithm can be redefined.
Type: Behavioral Class Pattern
Class Diagram:
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 { /** * 将数组array由小到大排序 * @param array */ protected abstract void sort(int[] array); public void showSortResult(int[] array){ this.sort(array); System.out.print("排序结果:"); for (int i = 0; i < array.length; i++){ System.out.printf("%3s", array[i]); } } }
After finishing writing, A went to 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 write the rest. Let’s implement 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 took 10 minutes to complete. 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; // 最小值变量 int indexMin = 0; // 最小值索引变量 int Temp; // 暂存变量 for (int i = index; i < array.length; i++) { if (array[i] < MinValue){ // 找到最小值 MinValue = array[i]; // 储存最小值 indexMin = i; } } Temp = array[index]; // 交换两数值 array[index] = array[indexMin]; array[indexMin] = Temp; } }
After writing it, hand it to A. A takes it and runs it:
public class Client { public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 预设数据数组 public static void main(String[] args){ AbstractSort s = new ConcreteSort(); sshowSortResult(a); } }
Running results:
Sort results: 0 1 3 4 5 7 9 10 12 32
Operating normally. 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 an (or a group of) implementation classes through an inheritance structure. There are three types of methods in abstract classes:
Abstract methods: The parent class only declares but does not implement them. Instead, it defines the specifications and then implements them by its subclasses.
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.
Hook method: declared and implemented by an 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 class extension method. 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 methods 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.
The above is the detailed content of An example introduction to the template method pattern in Java design patterns. For more information, please follow other related articles on the PHP Chinese website!