Template method model of design pattern learning

Template method pattern

Define the framework of an algorithm in operation, and delay some steps to subclasses. The template method pattern allows subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm. It is a code reuse technology based on inheritance and a behavioral model

Class Diagram

Insert picture description here

achieve

Abstract class

A series of basic operations are defined. These basic operations can be concrete or abstract. Each basic operation corresponds to a step of the algorithm, and these steps can be redefined or implemented in its subclasses. At the same time, a template method is implemented in the abstract class to define an algorithm framework. The template method can not only call the basic methods implemented in the abstract class, but also the basic methods implemented in the subclasses of the abstract class, and can also call Methods in other objects

package design.templatemethod.realize;

/*
 *
 *@author:zzf
 *@time:2020-12-21
 *
 */
public abstract class AbstractClass {
    
    
    //模板方法
    public void templateMethod(){
    
    
        
    }
    
    //基本方法——具体方法
    public void primitiveOperation1(){
    
    
        
    }
    //基本方法——抽象方法
    public abstract void primitiveOperation2();
    
    //基本方法——钩子方法
    public void primitiveOperation3(){
    
    
        
    }
}

Concrete sub-categories

package design.templatemethod.realize;

/*
 *
 *@author:zzf
 *@time:2020-12-21
 *
 */
public class ConcreteClass extends AbstractClass {
    
    
    @Override
    public void primitiveOperation2() {
    
    
        //实现
    }

    @Override
    public void primitiveOperation3() {
    
    
        //实现
    }
}

Applications

A software company wants to develop an interest calculation module for a bank’s business support system. The interest calculation process is as follows:
(1) The system verifies the user information according to the account number and password. If the user information is wrong, the system displays an error message.
(2) If the user information is correct, different interest calculation formulas are used to calculate interest according to different user types (for example, current accounts and fixed-term accounts have different interest calculation formulas).
(3) The system displays interest.
Now use the template method model to design the interest calculation module.
Insert picture description here

Code

Account class, acting as an abstract class

package design.templatemethod;

public abstract class Accout {
    
    

	// 基本方法:具体方法
	public boolean validata(String account, String password) {
    
    
		System.out.println("账号:" + account);
		System.out.println("密码:" + password);
		if (account.equalsIgnoreCase("张无忌") && password.equalsIgnoreCase("123456")) {
    
    
			return true;
		} else {
    
    
			return false;
		}

	}

	// 基本方法:抽象方法
	public abstract void calculateInterst();

	// 基本方法:具体方法
	public void display() {
    
    
		System.out.println("显示利息!");
	}

	// 模板方法
	public void handle(String account, String password) {
    
    
		if (!validata(account, password)) {
    
    
			System.out.println("账户或密码错误!");
			return;
		}
		calculateInterst();
		display();
	}
}

Concrete sub-categories

package design.templatemethod;

public class CurrentAccount extends Accout {
    
    

	// 覆盖父类抽象基本方法
	public void calculateInterst() {
    
    
		System.out.println("按活期利率计算利息!");

	}
}

package design.templatemethod;

public class SavingAccount extends Accout {
    
    

	@Override
	public void calculateInterst() {
    
    
		System.out.println("按定期利率计算利息!");

	}
}

Configuration file

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<className>design.templatemethod.CurrentAccount</className>
</config>

Tools

package design.templatemethod;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLUtil {
    
    

	public static Object getBean() {
    
    
		try {
    
    
			// 创建DOM文档对象
			DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = dFactory.newDocumentBuilder();
			Document doc;
			doc = builder.parse(new File("src//design//templatemethod//config.xml"));
			// 获取包含类名的文本节点
			NodeList nl = doc.getElementsByTagName("className");
			Node classNode = nl.item(0).getFirstChild();
			String cName = classNode.getNodeValue();

			// 通过类名生成实例对象
			Class c = Class.forName(cName);
			Object obj = c.newInstance();
			return obj;
		} catch (Exception e) {
    
    
			e.printStackTrace();
			return null;
		}
	}
}

Client

package design.templatemethod;

public class Client {
    
    

	public static void main(String[] args) {
    
    
		Accout accout;
		accout = (Accout) XMLUtil.getBean();
		accout.handle("张无忌", "123456");
	}
}

Insert picture description here
If you need to change the specific subclass, you only need to modify the configuration file to comply with the hook method of the opening and closing principle

A hook method has an abstract or concrete class declaration and implementation, and its subclasses may be extended. Usually the implementation given in the parent class is an empty implementation, and the empty implementation is used as the default implementation of the method. Of course, the hook method can also provide a non-empty default implementation

There are two types of hook methods in the template method pattern. The first type of hook method can be linked to some specific steps to implement different steps in the template method under different conditions. The return
type of this type of hook method is usually boolean type, method The name is generally isXXX(), which is used to judge a certain condition, if the condition is met, execute a certain step, otherwise it will not execute

The second type of hook methods are specific methods with empty implementation bodies, and subclasses can override or inherit these hook methods as needed. Compared with abstract methods, the advantage of this type of hook method is that if the subclass does not override the hook method defined in the parent class, the compilation can pass normally, but if the abstract method declared in the parent class is not covered, the compilation will report an error.

Use of hook methods

A software company wants to provide a data chart display function for the sales management system. The realization of this function includes the following steps:
(1) Obtain data from the data source
(2) Convert the data to XML format
(3) Use a certain chart method Display data
in XML format. This function supports multiple data sources and multiple chart display methods, but all chart display operations are based on XML format data, so it may be necessary to convert the data. If the data obtained from the data source is already XML data does not need to be converted

Code

Abstract parent class

package design.templatemethod.hookmethod;

/*
 *
 *@author:zzf
 *@time:2020-12-21
 *
 */
public abstract class DataViewer {
    
    
    //抽象方法,获取数据
    public abstract void getData();
    //具体方法,转换数据
    public void convertData(){
    
    
        System.out.println("将数据转换成XML格式");
    }
    //抽象方法,显示数据
    public abstract void displayData();
    //钩子方法,判断是否为XML格式数据
    public boolean isNotXMLData(){
    
    
        return true;
    }
    //模板方法
    public void process(){
    
    
        getData();
        //如果不是XML格式的数据则进行数据转换
        if(isNotXMLData()){
    
    
            convertData();
        }
        displayData();
    }
}

Concrete sub-categories

package design.templatemethod.hookmethod;

/*
 *
 *@author:zzf
 *@time:2020-12-21
 *
 */
public class XMLDataViewer extends DataViewer {
    
    
    @Override
    public void getData() {
    
    
        System.out.println("从XML文件中获取数据");
    }

    @Override
    public void displayData() {
    
    
        System.out.println("以柱状图显示数据");
    }

    //覆盖父类的钩子方法,返回false表示已经是XML格式数据,无需转换
    @Override
    public boolean isNotXMLData() {
    
    
        return false;
    }
}

Client

package design.templatemethod.hookmethod;

/*
 *
 *@author:zzf
 *@time:2020-12-21
 *
 */
public class Client {
    
    
    public static void main(String[] args) {
    
    
        DataViewer dv;
        dv=new XMLDataViewer();
        dv.process();
    }
}

operation result
Insert picture description here

Advantages and disadvantages of template method pattern

Advantages:
(1) Formally define an algorithm in the parent class, and its subclasses implement detailed processing. When the subclass implements the detailed processing algorithm, the execution order of the steps in the algorithm will not be changed
(2) The public behavior in the class library is extracted, and the public behavior is placed in the parent class, and different behaviors
can be realized through its subclasses. (3) A reverse control structure can be realized, and it has good scalability and conforms to a single responsibility Principles and Principles of Opening and Closing

Disadvantages : It is
necessary to provide a subclass for the different implementation of each basic method. If there are too many variable basic methods in the parent class, the number of classes will increase, the system will be larger, and the design will be more abstract

Applicable environment

(1) Implement the invariant part of an algorithm at a time, and leave the variable behaviors to subclasses to implement
(2) The common behaviors in each subclass should be extracted and concentrated in a common parent class to avoid code Repeat
(3) Need to determine whether a certain step in the parent class algorithm is executed through the subclass, so as to realize the reverse control of the subclass to the parent class

Refer to
Java design patterns

Guess you like

Origin blog.csdn.net/qq_43610675/article/details/111470028