The beginning is still the same kind of picture. Please look down
Zhang Wuji learned Taijiquan, forgot all the moves and knocked down the "two old men in the dark", the so-called "no moves in the heart". If you can learn all kinds of patterns at will, it can be said that you can forget all kinds of patterns at will.
What is the template pattern?
Template pattern is also a behavioral pattern, that is, a design pattern about what or how objects do. The essence of template pattern needs to define the framework of algorithm in operation, but there are some steps that do not need specific implementation, but different subclasses implement them respectively. Subclasses cannot modify the process framework, but some steps can be customized.
It mainly solves a problem: some general methods, but each subclass is rewritten, which is redundant.
For example, as like as two peas, the dishes are usually washed by pot, stir fried dishes, dishes, dishes, and vegetables. The details are different, but the other steps are almost identical. In this way, we can abstract the whole frame and repeat steps into the template. Different detail methods can be opened to each dish (specific implementation) to customize.
For example, when building a house, the construction of many places is the same: foundation, wall, water pipe, etc., but the internal design of different houses is different.
Do not use template mode
Just take a simple example of "stir fry". If the template mode is not used, sweet and sour carp:
public class SweetAndSourCarp { public void cookFood(){ washPan(); cook(); eat(); washDishes(); System.out.println(""); } private void washPan(){ System.out.print("Wash the pot --> "); } private void cook(){ System.out.print("Boiled sweet and sour carp --> "); } private void eat(){ System.out.print("having dinner --> "); } private void washDishes(){ System.out.print("Wash the dishes --> "); } }
To get another farmhouse fried meat, you need to write a lot of the same methods:
public class ShreddedPorkWithVegetables { public void cookFood(){ washPan(); cook(); eat(); washDishes(); System.out.println(""); } private void washPan(){ System.out.print("Wash the pot --> "); } private void cook(){ System.out.print("Fried farmhouse fried meat --> "); } private void eat(){ System.out.print("having dinner --> "); } private void washDishes(){ System.out.print("Wash the dishes --> "); } }
The test classes are as follows:
public class Test { public static void main(String[] args) { SweetAndSourCarp sweetAndSourCarp = new SweetAndSourCarp(); sweetAndSourCarp.cookFood(); ShreddedPorkWithVegetables shreddedPorkWithVegetables = new ShreddedPorkWithVegetables(); shreddedPorkWithVegetables.cookFood(); } }
Test results:
Wash the pot --> Boiled sweet and sour carp --> having dinner --> Wash the dishes --> Wash the pot --> Fried farmhouse fried meat --> having dinner --> Wash the dishes -->
It can be seen that the overall process is the same. Some steps are the same and some steps are different, but the template mode is not used. Each class needs to rewrite the method. Even for general methods, the whole process needs to write it by itself.
Optimize using template mode
If we use the template pattern, we will abstract an abstract class, define the overall process, have fixed steps, open the methods that need to be customized, and let the specific implementation classes customize according to their own needs.
Abstract classes defined:
public abstract class CookFood { public final void cookFood() { washPan(); cook(); eat(); washDishes(); System.out.println(""); } private final void washPan() { System.out.print("Wash the pot --> "); } public abstract void cook(); private final void eat() { System.out.print("having dinner --> "); } private final void washDishes() { System.out.print("Wash the dishes --> "); } }
Specific implementation of sweet and sour carp:
public class SweetAndSourCarp extends CookFood { @Override public void cook() { System.out.print("Boiled sweet and sour carp --> "); } }
Farmhouse fried meat:
public class ShreddedPorkWithVegetables extends CookFood { @Override public void cook() { System.out.print("Fried farmhouse fried meat --> "); } }
The test class is the same as before, and the test results are the same. It will not be repeated here.
In the above methods, we only open the cook() method, which is the hook method:
In the parent class of the template method pattern, we can define a method that does nothing by default. The subclass can override it or not according to the situation. This method is called "hook method"
Hook methods are open and can be overwritten by subclasses at will. However, like other methods above, we don't want subclasses to rewrite or overwrite it. We can use the final keyword to prevent subclasses from rewriting template methods.
Application of template mode
In fact, the template mode is used in the Thread implementation of JDK. We know that there are two ways to create threads:
- Create Thread class
- Implement runnable interface
We usually implement the run() method, but we call the start() method to start the thread. This is because the start() method helps us call the run() method. The run() method is a developed method, and we can overwrite it.
Start0() is a native method, which is implemented by c language. When calling, we really call our run() method. If we need to track this method, we need to go to the bottom of HotSpot. The purpose of this introduction is to let you know that it also uses the template mode.
private native void start0();
For native keywords, please refer to: http://aphysia.cn/archives/na...
Advantages and disadvantages of template mode
Advantages of template mode:
- 1. Encapsulate the fixed parts, expand the parts that need to be customized and modified, and comply with the opening and closing principle.
- 2. The common code is in the parent class and easy to maintain.
- 3. The whole process is controlled by the parent class, which is convenient to adjust.
Disadvantages:
- 1. There may be many subclasses, and the system complexity increases.
- 2. Only a small part of the subclass is implemented. To understand all the methods, you need to read them in the parent class, which affects the reading of the code.
Conclusion: the complex details of the code should be hidden, open and customized, elegant!
Design pattern series:
- Design mode [1] - how to write single case mode?
- Design pattern [1.1] - how do you want to break the singleton pattern?
- Design pattern [1.2] - is enumerative singleton so useful?
- Design pattern [1.3] - why is starving singleton thread safe?
- Design mode [2] - simple factory mode?
- Design mode [2.1] - how did the simple factory mode evolve into the factory method mode?
- Design pattern [2.2] - how does the factory pattern evolve into an abstract factory pattern?
- Design pattern [3.1] - on the static, dynamic and cglib agent of agent pattern
- Design pattern [3.2] - how fragrant is JDK dynamic agent source code analysis?
- Design pattern [3.3] - Interpretation of CGLIB dynamic agent source code
- Design mode [4] - detailed explanation of builder mode
- Design mode [5] - prototype mode
- Design mode [6.1] - Discussion on adapter mode
- Design mode [6.2] - talk about adapter mode again
- Design mode [7] - explore the bridging mode
- [design mode] - manual mode
- Design mode [9] - appearance mode? Not so tall
- Design mode [10] - by the way, take a look at the sharing mode
- Design mode [11] - combination mode
- Design mode [12] - the strategy mode to solve the recent fire
[about the author]:
Qin Huai, the official account of Qin Huai grocery store, author's personal website: http://aphysia.cn , the road of technology is not for a while, with high mountains and long rivers. Even if it is slow, it will gallop without stopping.