Template method pattern, the name is very direct, and easy to understand. What is a template? A template is a set of fixed formats. We can imagine an ordinary worker's daily work template: go to work - > work - > go home from work.
For each employee, the specific content of the three steps is different, but the process is the same.
In the development process, the architect or senior developer will write some method flow, specify the method name, method output, execution sequence, etc., but the method body is empty, leaving the primary developers to fill in the specific implementation functions.
Moreover, such a set of templates can be implemented in different platform languages to generate products of different platforms. These solutions can be called template method patterns.
Definition
Define the framework of the algorithm in an operation, and defer some steps to subclasses. Template method pattern enables subclasses to redefine some specific steps of an algorithm without changing its structure.
Use scenarios
- Multiple logics have common methods, and the logic is basically the same.
- Important and complex algorithms can be designed as template methods, and the peripheral details can be realized by various subclasses.
- Template methods are often used in refactoring, extracting the same code into the parent class, and then constraining its behavior through hook methods.
UML
UML diagrams are simple
- Abstemplate: An Abstract class, which defines a set of algorithmic frameworks
- ConcreteImplA: Specific implementation class A
- ConcreteImplB: Specific Implementation Class B
Simple examples
Here's an example of the process of turning on a computer. Although computers have different systems and uses, the process of starting a computer is the same.
Start Power Supply -> Check System Status -> Enter Operating System -> Authenticate Authentication Logon
Define an abstract computer template
public abstract class AbsComputer {
protected void powerOn(){
System.out.println("Turn on the power supply");
}
protected void checkHardware(){
System.out.println("Check Hardware");
}
protected void loadOS(){
System.out.println("Loading Operating System");
}
protected void login(){
System.out.println("User login");
}
//No rewriting is allowed here. It must be done in this order.
public final void startUp(){
System.out.println("Boot up START");
checkHardware();
loadOS();
login();
System.out.println("Boot up END");
}
}
Implementing a programmer computer
public class CoderComputer extends AbsComputer {
@Override
protected void login() {
super.login();
System.out.println("Programmer computers need to verify user names and passwords");
}
}
Implementing an Oxforcing Computer
public class NBComputer extends AbsComputer {
@Override
protected void checkHardware() {
super.checkHardware();
System.out.println("Niubi's computer needs to verify the hardware firewall");
}
@Override
protected void login() {
super.login();
System.out.println("Niuquan's computer needs to verify fingerprints");
}
}
Use:
public class Client {
public static void main(String[] args) {
CoderComputer coderComputer = new CoderComputer();
coderComputer.powerOn();
coderComputer.startUp();
System.out.println("--------");
NBComputer nbComputer = new NBComputer();
nbComputer.powerOn();
nbComputer.startUp();
}
}
Output:
Subclasses can only modify part of the specific implementation, the overall logic process is not allowed to modify.
Template Method in Android
The common use of AsyncTask is as follows:
class MyAsynctask extends AsyncTask{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Object doInBackground(Object[] params) {
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}
Usually there are three ways to rewrite. The execution process of AsyncTask is a logical process, in which three methods are executed at the appropriate time, and the process is fixed. However, subclasses can change the specific content of execution through three methods of rewriters.
summary
Template method pattern is process encapsulation, the parent class extracts common code, and the subclass implements part or all of the steps. The parent class specifies the overall process.
Advantage
- The invariant part is encapsulated and the variable part is expanded, which conforms to the open-close principle.
- Extract common code, improve code reuse rate and facilitate maintenance.
shortcoming
- It is difficult for users to read code only by looking at subclasses, because subclasses are not a complete logic.