/**
*抽象模板
*/
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+"毫秒");
}
}