定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
模板类
/**
* @Author: chuan.bai
* @Description 定义组装电脑的工序
* @Date: Created on 15:58 2021/3/26
* @Modified By:
*/
public abstract class AssemblingComputerTemplate {
public abstract void addCpu();
public abstract void addDisk();
public abstract void addVideoCard();
//开始组装
public void startAssembling(){
//组装cpu
addCpu();
//组装硬盘
addDisk();
//组装显卡
addVideoCard();
}
}
具体实现类
/**
* @Author: chuan.bai
* @Description 组装戴尔电脑具体操作
* @Date: Created on 16:04 2021/3/26
* @Modified By:
*/
public class DellComputer extends AssemblingComputerTemplate {
@Override
public void addCpu() {
System.out.println("DellComputer.addCpu");
}
@Override
public void addDisk() {
System.out.println("DellComputer.addDisk");
}
@Override
public void addVideoCard() {
System.out.println("DellComputer.addVideoCard");
}
}
/**
* @Author: chuan.bai
* @Description 组装联想电脑具体操作
* @Date: Created on 16:03 2021/3/26
* @Modified By:
*/
public class LenovoComputer extends AssemblingComputerTemplate{
@Override
public void addCpu() {
System.out.println("LenovoComputer.addCpu");
}
@Override
public void addDisk() {
System.out.println("LenovoComputer.addDisk");
}
@Override
public void addVideoCard() {
System.out.println("LenovoComputer.addVideoCard");
}
}
工人类,任务是制作电脑
/**
* @Author: chuan.bai
* @Description 工人类,任务是制作电脑
* @Date: Created on 16:05 2021/3/26
* @Modified By:
*/
public class Worker {
public static void main(String[] args) {
AssemblingComputerTemplate dellComputer = new DellComputer();
dellComputer.startAssembling();
AssemblingComputerTemplate lenovoComputer = new LenovoComputer();
lenovoComputer.startAssembling();
}
}
网友评论