/*
需求:获取一段程序运行的时间
原理:获取程序开始和结束的时间并相减即可。
获取时间:System.currentTimeMillis();
当代码完成优化后,就可以解决这类问题,这种方式,模板方法设计模式。
模板方法设计模式:在定义功能时,功能的一部分是确定的,一部分是不确定德尔,而确定的部分在使用不确定的部分,
那么这时就将不确定的部分暴露出去,由该类的子类去完成
*/
abstract class GetTime
{
public final void getTime()//因为这个类就是用来获取时间的,所以子类中不能复写,如果复写此类就没有意义了
{
long start = System.currentTimeMillis();//获取开始的时间
runcode();
long end = System.currentTimeMillis();//获取结束的时间
System.out.print("毫秒:" + (end - start));
}
public abstract void runcode();//由于代码不确定,并且还要执行,所以定义为抽象,在子类中复写
}
class SubTime extends GetTime
{
public void runcode()
{
for(int x = 0; x < 1000; x++)
{
System.out.print(x);
}
}
}
class Template
{
public static void main(String[] args)
{
//GetTime gt = new GetTime();
SubTime gt = new SubTime();
gt.getTime();
}
}
模板方法设计模式练习
最新推荐文章于 2025-09-12 14:39:04 发布