/**
*抽象模板
*/
abstract class CalTimeTemplate{
/**
*在抽象模板中定义一个抽象方法,这个方法是为了让子类去实现
*/
public abstract void doJob();
/**定义一个回调方法,用于扩展
*/
public void expandMethod(){
System.out.println("运行开始");
}
/**
*定义抽象模板中的子类不可修改的方法
*/
private final long getCurrentTime(){
return System.currentTimeMillis();
}
/**
*模板方法
*/
public long templateMethod(){
expandMethod();
//获得当前时间的毫秒数
long startTime = getCurrentTime();
doJob();
//获得当前时间的毫秒数
long endTime = getCurrentTime();
return endTime - startTime;
}
}
/**
*定义具体模板
*/
class ConcrateTemplate extends CalTimeTemplate{
public void doJob(){
for(int i=0; i<100; i++){
System.out.println(i+"%"+"正在执行");
}
}
}
class TemplateTest1{
public static void main(String []args){
ConcrateTemplate ct = new ConcrateTemplate();
long times = ct.templateMethod();
System.out.println("程序执行了"+times+"毫秒");
}
}
本文介绍了一个使用模板方法设计模式的示例,通过定义一个抽象模板类来实现算法骨架,并允许子类提供特定实现。具体模板类继承自抽象模板类并实现了抽象方法,展示了如何计算程序执行的时间。

被折叠的 条评论
为什么被折叠?



