The book "Design Patterns" describes this in the template method model:
Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The steps to redefine the algorithm without changing its structure.
My understanding: Defining an abstract class or interface, defining some abstract methods within it (for Templatemethod calls) and a Templatemethod method (not abstract methods), and an interface or abstract class that encapsulates these abstract methods is the skeleton. and delay its implementation to subclasses, that is, to implement it with subclasses. The steps to redefine the algorithm without changing its structure are to rewrite or implement these Templatemethod abstract methods of the parent class. An example is given below:
abstract class QueryTemplate{
public void doQuery(){ //Template Method
formatConnect();
formatSelect();
}
protected abstract void formatConnect();
protected abstract void formatSelect();
}
class OracleQT extends QueryTemplate{
public void formatConnect() {
System.out.println("格式化Qracle数据库连接");
}
public void formatSelect() {
System.out.println("格式化Oracle数据库查询");
}
}
class MysqlQT extends QueryTemplate{
public void formatConnect() {
System.out.println("格式化Mysql数据库连接");
}
public void formatSelect() {
System.out.println("格式化Mysql数据库查询");
}
}
public class client {
public static void main(String[] args) {
QueryTemplate oracleQT=new OracleQT();
oracleQT.doQuery();
QueryTemplate mysqlQT=new MysqlQT();
mysqlQT.doQuery();
}
}
Output results:
Format Qracle Database connection
Format Oracle Database queries
Format MySQL database connection
Format MySQL database query
In this example, we define a skeleton querytemplate, define a template method in its interior, and some steps (abstract methods), and invoke these steps using template. The steps are implemented in a subclass.
Summary: Sometimes, a process that is composed of a series of steps needs to be executed. The process is the same at a high level, but some steps may be implemented differently. Just as, querying a SQL database is the same at a high level, but some details such as how to connect to a database may vary depending on the details of the platform. With the template method pattern, we can first define the sequence of steps and then cover the steps that need to be changed.