A brief introduction to the template method
1. What is a template pattern
Template Method Pattern, also known as Template Pattern, is a kind of behavioral design Pattern. It allows subclasses to redefine specific steps of an algorithm without changing the structure of the algorithm by defining the algorithm framework in an operation and deferring the implementation of some steps to subclasses.
2. Simple examples
What do you like for breakfast? As a child growing up in the north, soy milk oil sticks are the most common collocation in my hometown. Speaking of soya-bean milk, we have to say soya-bean milk types, soybeans, black beans, mung beans and so on. Although the raw materials are different, the process used to make each soymilk is very similar.Normally we make soybean milk in four steps:
- Soak the prepared beans in water
- Break the soaked beans in a soy milk machine
- Separate the broken bean dregs from the raw bean milk
- Cooked soybean milk
Although the general steps are so, but due to the different raw materials, the specific operation of each step may still have a slight gap, so how do we design a code, can not only realize the function of making soybean milk, but also reflect the differences in the process of making different soybean milk?
Second, the implementation of template mode
1. Code implementation of template pattern
The template pattern is very simple. If you look at my example code, you will notice that you are writing the template pattern every day. Make soybean milk abstract class
public abstract class Milk {
/ / soak
abstract void soak(a);
/ / broken
abstract void attrite(a);
/ / separation
abstract void separate(a);
/ / cooked
abstract void cook(a);
// Make soybean milk
public final void make(a) { soak(); attrite(); separate(); cook(); }}Copy the code
Respectively prepare mung bean milk and soybean milk code soybean milk
public class Soy extends Milk {
@Override
void soak(a) {
System.out.println("Soya beans are soaked in water.");
}
@Override
void attrite(a) {
System.out.println("Soybeans are crushed in a soy milk machine.");
}
@Override
void separate(a) {
System.out.println("The soybean dregs are separated.");
}
@Override
void cook(a) {
System.out.println("Soy bean milk has been made."); }}Copy the code
Mung bean soya-bean milk
public class Urad extends Milk {
@Override
void soak(a) {
System.out.println("Mung beans are soaked in water.");
}
@Override
void attrite(a) {
System.out.println("Mung beans are crushed in a soy milk machine.");
}
@Override
void separate(a) {
System.out.println("Mung bean residue is separated.");
}
@Override
void cook(a) {
System.out.println("Mung bean milk has been made."); }}Copy the code
3. Test code
public class Client {
public static void main(String[] args) {
Milk soy = newSoy(); soy.make(); }}Copy the code
Test results: Here we see a cup of soy beans and soy milk is just done. The above code is a simple template pattern implementation, is not very simple, I am not lie to you ~ this is mainly due to Java’s own polymorphic characteristics and template pattern design idea is very consistent, do not believe it let us look at the template pattern design class diagram is not a polymorphic inheritance diagram:We can see from the diagram that the main components of the template pattern are divided into two parts:
- An abstract class that defines abstract behavior and template methods
- A subclass responsible for implementing an abstract method
Isn’t it very simple ~
One thing to note here is that to prevent malicious manipulation, template methods are final and cannot be overwritten!
Third, the expansion of template method
1. Hook method
Before we talk about hook methods, let’s take a quick look at the classification of methods in template patterns. Let’s review the definition of a template pattern: a design pattern that allows a subclass to redefine specific steps of an algorithm without changing the structure of the algorithm by defining the framework of the algorithm in an operation and deferring the implementation of some of the steps to a subclass. To achieve this, there are two main categories of methods designed in the template pattern:
- Basic method: mainly responsible for defining the behavior of the object, its main concern is the implementation of the algorithm in detail.
- The template method is responsible for defining an algorithm structure, in other words, defining the basic logic for an algorithm to run.
And the basic methods are mainly divided into three kinds:
- Abstract methods: declared by an abstract superclass and implemented by subclasses, are responsible for declaring some behavior of an object.
- Concrete methods: declared and implemented by an abstract superclass, not implemented or overridden by subclasses, essentially define a universal method.
- Hook methods: declared and implemented by abstract classes, subclasses can optionally extend them. Typically, an abstract class is responsible for declaring an empty implementation hook method, and then implementing the logic when a subclass needs to use the method. It is important to note that the hook method itself is no different from the concrete method at the code level, just a design difference. In short, the hook method provides an option for all subclasses, and the concrete method is mandatory for all subclasses.
Here we will talk specifically about the hook method code implementation:
Let’s go back to the example of soy milk. In the existing soy milk production process, maybe soy milk with sugar is better but mung bean milk is not suitable for sugar. In this case, what changes do we need to make to the code?
1. Added a sugared hook method to the abstract class
public abstract class Milk {
/ / soak
abstract void soak(a);
/ / broken
abstract void attrite(a);
/ / separation
abstract void separate(a);
/ / cooked
abstract void cook(a);
abstract Boolean isSugar(a);
// Make soybean milk
public final void make(a) {
soak();
attrite();
separate();
cook();
sugar();
}
/ / sugar
protected void sugar(a) {
if(isSugar()) {
System.out.println("Sugar"); }}}Copy the code
2. Modify soybean milk, copy the method of adding sugar
public class Soy extends Milk {
@Override
void soak(a) {
System.out.println("Soya beans are soaked in water.");
}
@Override
void attrite(a) {
System.out.println("Soybeans are crushed in a soy milk machine.");
}
@Override
void separate(a) {
System.out.println("The soybean dregs are separated.");
}
@Override
void cook(a) {
System.out.println("Soy bean milk has been made.");
}
@Override
protected void sugar(a) {
System.out.println("Sugar");
}
@Override
Boolean isSugar(a) {
// TODO Auto-generated method stub
return true; }}Copy the code
Test results:
public class Client {
public static void main(String[] args) {
Milk soy = newSoy(); soy.make(); }}Copy the code
2. Application of template pattern in Java language
(1) Custom lock
What if we want to customize a synchronizer? This time the easiest way is to inherit AQS class (AbstractQueuedSynchronizer) then implement some of those methods. Due to the limited space, here will not be repeated, interested students can consult the relevant information of the custom lock.
Four,
1. Design class diagram of template pattern
We can see from the diagram that the main components of the template pattern are divided into two parts:
- An abstract class that defines abstract behavior and template methods
- A subclass responsible for implementing an abstract method
2. Advantages and disadvantages of the template pattern
Advantages:
- High expansibility
- Common code is extracted and easy to maintain
- The behavior is controlled by the parent class, and the child class is only responsible for maintenance, in accordance with the open closed principle
disadvantages
- This makes the code more difficult to understand
3. Application scenarios of the template mode
- Multiple subclasses have public methods and basically the same logic
- For important and complex algorithms, you can design the core algorithm as a template algorithm and then hand over the implementation details to subclasses
- In refactoring, the template pattern is a very common one that extracts the same code into a parent class and then constrains its behavior through hook methods
Five, the conclusion
Today’s proxy mode explanation is all over, the related code of the design mode has been included in Gitee, you can take it directly if you need it:
Gitee.com/xiaolong-ob…
If you have any questions, you are welcome to leave a message in the comment section or send a private message to the blogger, who will answer them for you in the first time. The code word is not easy, feel the harvest of friends remember to pay attention to the blogger, do not be white whoring monster oh ~ blogger here wish you can be promoted in the New Year, to the peak of life!