//思想:模板方法设计模式
/*
需求:获取一段程序运行的时间.
原理:获取程序开始和结束的运行时间,想减即可.
用到系统提供的方法:System.currentTimeMillis()
*/
//定义一个获取时间的类GetTime
abstract class GetTime
{
//定义一个获取时间的方法,该方法是确定的.为子类提供获取特定一段程序的运行时间,所以它是不能够被更改的(重写),修饰符final
public final long getTime()
{
long startTime=System.currentTimeMillis();
runCode();
long endTime=System.currentTimeMillis();
long runTime=endTime-startTime;
return runTime;
}
//定义一个runCode()方法,用来表示子类特定的一段程序的运行代码.既然是特定的,说明它是不确定的,所以该方法允许被重写的.应该用abstract修饰符(这里不考虑默认一段程序的运行时间,所以用的是抽象方法)
public abstract void runCode();
}
class SubTime extends GetTime
{
public void runCode()
{
for(int i=0;i<234;i++)
System.out.print(i);
}
}
class TemplateDemo2
{
public static void main(String[] args)
{
SubTime st=new SubTime();
long runTime=st.getTime();
System.out.println();
System.out.println(runTime);
}
}