当前位置:网站首页>Introduction and example of template method mode
Introduction and example of template method mode
2022-06-30 21:42:00 【Dog snake】
Catalog
One 、 Introduction to template method mode
One 、 Introduction to template method mode
The core design idea of template method mode is through An abstract class publicly defines the execution order of abstract methods , And set the abstract method to have only Subclass to implement , But do not design independent access methods . That is, the abstract methods implemented by subclasses cannot be accessed by other classes , The execution order logic of all abstract methods is controlled by the public methods in the abstract class .
Problem solved : The methods of some business scenarios in the system can be universal , Each subclass needs to implement this method again .
When to use : Some common implementation methods can be used .
Use scenarios : 1、 There are methods common to many subclasses , And the logic is the same . 2、 Important or complex methods are considered as template methods .
Two 、 Code example
First, let's take a look at the business model : Suppose we now have an import excel Functions of tables , But imported excel Tables vary with business differences , But they all belong to this system .
In order to improve efficiency , It is not necessary for every business to implement a set of file import logic , We can define a set of Excel Imported business logic template , Of any subsequent business Excel Import only needs to inherit the defined template to implement their own methods .
Now let's simulate the implementation process according to the business scenario described above :

1. Business dto: User category and commodity category ;
@Data
public class UserImportDto {
/**
* User name
*/
private String name;
/**
* Home address
*/
private String message;
/**
* Age
*/
private Integer age;
}@Data
public class ProductDto {
/**
* Name of commodity
*/
private String productName;
/**
* Commodity code
*/
private String productCode;
/**
* Product usage information
*/
private String productInfo;
/**
* commodity price
*/
private BigDecimal price;
}2. Core abstract template class :
/**
* Different business Excel Table import public implementation template ;
* If all of the systems excel All imports use public templates , Except the business is different , The import process is the same .
*/
@Slf4j
public abstract class ImportTemplate<T> {
public Result importMethod(String fileName) {
// 1. Get the column header information of the template file and the imported file
String fileHeadTemplate = fileHeadTemplate();
String columnHeads = getColumnHeads(fileName);
// 2. Verify whether the column header of the imported data matches the template ;
Boolean checkHeads = checkFileColumnHead(fileHeadTemplate,columnHeads);
if (!checkHeads) {
return Result.err(" The column header of the import file is inconsistent with the defined table column header !");
}
// 3. If the column head meets the requirements , Get the data in the table
List<T> dataList = getFileData(fileName);
if (CollectionUtils.isEmpty(dataList)) {
log.info(" Business data not obtained , Import failed !");
return Result.err(" The imported business data was not obtained !");
}
// 4. The imported data is subject to respective business verification
Boolean ok = checkDataList(dataList);
if (!ok) {
return Result.err(" Data service verification failed !");
}
// 5. Business verification passed , Save the data
saveData(dataList);
return Result.ok(" Successful import !");
}
/**
* Need to import excel Table column header style ;
* @return
*/
protected abstract String fileHeadTemplate();
/**
* Get the column header of the import file ;
*
* @return
*/
protected abstract String getColumnHeads(String fileName);
/**
* Verify whether the imported column header is consistent with the template sample ;
*
* @return
*/
protected abstract Boolean checkFileColumnHead(String fileHeadTemplate,String columnHeads);
/**
* Get import data
*
* @return
*/
protected abstract List<T> getFileData(String fileName);
/**
* Perform various business verifications on the imported data
*
* @param dataList
* @return
*/
protected abstract Boolean checkDataList(List<T> dataList);
/**
* The verified data is imported to the server or recorded in the database ;
* @param list
*/
protected abstract void saveData(List<T> list);
}3. Template implementation class : user Excel Import and product Excel Import
@Slf4j
public class UserInfoImport extends ImportTemplate<UserImportDto> {
@Override
protected String fileHeadTemplate(){
log.info(" user excel Form template ==={}"," User name , Home address , Age ");
return " User name , Home address , Age ";
}
@Override
protected String getColumnHeads(String fileName) {
// The business logic of actually obtaining the column header information of the user's imported file is omitted here , The focus of non design patterns ;
log.info(" Get the header of the user import file ==={}"," User name , Home address , Age ");
return " User name , Home address , Age ";
}
@Override
protected Boolean checkFileColumnHead(String fileHeadTemplate,String columnHeads) {
// If the column header of the import file is consistent with the column header defined by the template , Check by
if(fileHeadTemplate.equals(columnHeads)){
log.info(" user excel Table import file header verification passed ");
return true;
}
return false;
}
@Override
protected List<UserImportDto> getFileData(String fileName) {
// Simulation from Linux Get the data of the imported file from the file server
List<UserImportDto> list = new ArrayList<>();
log.info(" Get and import user data ");
// Business code omitted ...
return list;
}
@Override
protected Boolean checkDataList(List<UserImportDto> dataList) {
// Perform business verification on the obtained data , For example, the name must be filled in ;
for(UserImportDto userImportDto : dataList){
if(StringUtils.isEmpty(userImportDto.getName())){
return false;
}
}
log.info(" The imported user data has passed the verification ");
return true;
}
@Override
protected void saveData(List<UserImportDto> list) {
// Simulate the actual business logic of saving user data
// The code of data warehousing or storage file is omitted ...
log.info(" User data saved successfully !");
}
}@Slf4j
public class ProductImport extends ImportTemplate<ProductDto> {
@Override
protected String fileHeadTemplate() {
log.info(" goods excel Form template ==={}"," User name , Home address , Age ");
return " Name of commodity , Commodity code , Product usage information , commodity price ";
}
@Override
protected String getColumnHeads(String fileName) {
// The business logic for actually obtaining the column header information of the commodity import file is omitted here , The focus of non design patterns ;
log.info(" Get the header of the product import file ==={}"," Name of commodity , Commodity code , Product usage information , commodity price ");
return " Name of commodity , Commodity code , Product usage information , commodity price ";
}
@Override
protected Boolean checkFileColumnHead(String fileHeadTemplate, String columnHeads) {
// If the column header of the import file is consistent with the column header defined by the template , Check by
if (fileHeadTemplate.equals(columnHeads)) {
log.info(" goods excel Table import file header verification passed ");
return true;
}
return false;
}
@Override
protected List<ProductDto> getFileData(String fileName) {
// Simulate obtaining data of imported files from a special file ECs
List<ProductDto> list = new ArrayList<>();
ProductDto productDto = new ProductDto();
productDto.setProductName(" wahaha ");
productDto.setProductCode("123");
productDto.setProductInfo(" You can drink AD Calcium milk ");
productDto.setPrice(new BigDecimal("1"));
list.add(productDto);
log.info(" Get imported product data ");
// Business code omitted ...
return list;
}
@Override
protected Boolean checkDataList(List<ProductDto> dataList) {
// Perform business verification on the obtained data , For example, the name must be filled in ;
for (ProductDto userImportDto : dataList) {
if (StringUtils.isEmpty(userImportDto.getProductCode())) {
return false;
}
}
log.info(" The imported product data has passed the verification ");
return true;
}
@Override
protected void saveData(List<ProductDto> list) {
// Simulate the actual commodity storage data business logic
// The code of data warehousing or storage file is omitted ...
log.info(" Commodity data saved successfully !");
}
}4. Test class :
public class TemplateModelDemo {
public static void main(String[] args) {
System.out.println(" No user information in the simulated imported user table ");
ImportTemplate userInfoImport = new UserInfoImport();
userInfoImport.importMethod("xxxx");
System.out.println(" Simulate the import of commodity tables containing commodity information ");
ImportTemplate productImport = new ProductImport();
productImport.importMethod("xxxx");
}
}5. test result :

3、 ... and 、 summary
From the above implementation, we can see that the template method pattern is very convenient in defining a unified structure, that is, implementing standards , It can make the subsequent implementers do not care about the calling logic , Just follow the uniform method .
in addition , The template method pattern is also used to solve the common methods of subclasses , Put it into the parent class for optimization design . Let each subclass only do what subclasses need to do , Without concern for other logic .
Simple summary : Behavior is managed by the parent class , The variable extension part is implemented by each subclass .
边栏推荐
- The Jenkins download Plug-in can't be downloaded. Solution
- 1-18 create the most basic express server & API module for creating routes
- 升级kube出现unknown flag: --network-plugin
- Icml2022 | utility theory of sequential decision making
- Some problems when SSH default port is not 22
- Ml & DL: introduction to hyperparametric optimization in machine learning and deep learning, evaluation index, over fitting phenomenon, and detailed introduction to commonly used parameter adjustment
- Troubleshooting the problem of pytorch geometric torch scatter and torch spark installation errors
- Coefficient of variation method matlab code [easy to understand]
- Three techniques for reducing debugging time of embedded software
- 1-3 using SQL to manage databases
猜你喜欢

Radar data processing technology

Text recognition svtr paper interpretation

jupyter notebook/lab 切换conda环境

pytorch geometric torch-scatter和torch-sparse安装报错问题解决

Deployment and use of Nacos

Prediction and regression of stacking integrated model

《ClickHouse原理解析与应用实践》读书笔记(3)

1-2 安装并配置MySQL相关的软件

Akk bacteria - the next generation of beneficial bacteria

qsort函数和模拟实现qsort函数
随机推荐
ClickHouse distributed表引擎
5G 在智慧医疗中的需求
《ClickHouse原理解析与应用实践》读书笔记(1)
Open source internship experience sharing: openeuler software package reinforcement test
笔记【JUC包以及Future介绍】
興奮神經遞質——穀氨酸與大腦健康
Reading notes of Clickhouse principle analysis and Application Practice (3)
Jupyterbook clear console output
VIM common shortcut keys
兴奋神经递质——谷氨酸与大脑健康
How to run jenkins build, in multiple servers with ssh-key
jupyter notebook/lab 切换conda环境
给苏丹国安德森苏丹的撒过 d s g
jenkins下载插件下载不了,解决办法
1-2 install and configure MySQL related software
的撒啊苏丹看老司机
Rethink healthy diet based on intestinal microbiome
1-19 using CORS to solve interface cross domain problems
Fletter nested hell? No, constraintlayout to save!
做一个 Scrollbar 的思考