软件设计模式(Design pattern),又称设计模式,是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。
汇总目录链接:【玩转23种Java设计模式】学习目录汇总整理
模板方法模式(Template Method Pattern),又叫模板模式(Template Pattern), 它是一种行为设计模式, 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构,就可以重定义该算法的某些特定步骤。
角色:
文件处理,公共下载和公共读取,特定处理数据。
@Slf4j
public abstract class AbstractTemplate {
public void execute(String filePath) {
download(filePath);
read(filePath);
deal(filePath);
}
public void download(String filePath) {
log.info("公共下载:{}", filePath);
}
public void read(String filePath) {
log.info("公共读取:{}", filePath);
}
public abstract void deal(String filePath);
}
@Slf4j
public class OneFileService extends AbstractTemplate {
@Override
public void deal(String filePath) {
log.info("OneFileService 处理数据:{}", filePath);
}
}
@Slf4j
public class TwoFileService extends AbstractTemplate {
@Override
public void deal(String filePath) {
log.info("TwoFileService 处理数据:{}", filePath);
}
}
public class Main {
public static void main(String[] args) {
OneFileService oneFileService = new OneFileService();
oneFileService.execute("D:\\test.txt");
}
}
公共下载:D:\test.txt
公共读取:D:\test.txt
OneFileService 处理数据:D:\test.txt