您的位置:首页 > 其它

抽象模板-计算程序的执行时间

2017-11-27 18:26 183 查看
/**

*抽象模板

*/

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+"毫秒");
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  抽象模板