1. 需求
需求:获取一段程序运行的时间。
原理:获取程序开始和结束的时间并相减。
获取时间:System.currentTimeMillis();
System.currentTimeMillis():产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数。
2. 例子1
class GetTime
{
public void getTime()
{
long start=System.currentTimeMillis();
for(int x=0;x<1000;x++)
{
System.out.print(x);
}
long end=System.currentTimeMillis();
System.out.println("毫秒“+(end-start));
}
}
class TemplateDemo
{
public static void main(String[] args)
{
GetTime gt=new GetTime();
gt.getTime();
}
}
3. 例子2
运行的功能可能是不确定的,可能每次都要修改
for(int x=0;x<1000;x++)
{
System.out.print(x);
}
不建议直接在类GetTime里面改
解决方法:复写掉该函数
class GetTime
{
public void getTime()
{
long start=System.currentTimeMillis();
for (int x=0;x<1000;x++ )
{
System.out.print(x);
}
long end=System.currentTimeMillis();
System.out.println("毫秒"+(end-start));
}
}
class SubTime extends GetTime
{
public void getTime()
{
long start=System.currentTimeMillis();
for (int x=0;x<4000;x++ ) //改写代码
{
System.out.print(x);
}
long end=System.currentTimeMillis();
System.out.println("毫秒"+(end-start));
}
}
class TemplateDemo
{
public static void main(String[] args)
{
SubTime st=new SubTime();
st.getTime();
}
}
4. 例子3
用复写该函数的方法发现,程序的重复性很高。
可以只修改部分函数
for(int x=0;x<1000;x++)
{
System.out.print(x);
}
将以上代码封装起来
class GetTime
{
public void getTime()
{
long start=System.currentTimeMillis();
runCode();
long end=System.currentTimeMillis();
System.out.println("毫秒"+(end-start));
}
public void runCode()
{
for (int x=0;x<1000;x++ )
{
System.out.print(x);
}
}
}
class SubTime extends GetTime
{
public void runCode() //只复写一部分函数
{
for (int x=0;x<4000;x++ )
{
System.out.print(x);
}
}
}
class TemplateDemo
{
public static void main(String[] args)
{
SubTime st=new SubTime();
st.getTime();
}
}
5. 例子4
定义一个获取时间的功能类,里面的具体运行程序功能是不确定的,
该方法体的具体内容可能写不出来,只是知道有这个方法体。
用抽象的方法来解决
abstract class GetTime //有抽象函数,类也要用abstract修饰
{
public final void getTime() //本类的功能是要获取时间,用final控制不能被复写
{
long start=System.currentTimeMillis();
runCode();
long end=System.currentTimeMillis();
System.out.println("毫秒"+(end-start));
}
public abstract void runCode(); //提供一个方法入口给子类,不确定具体的内容
}
class SubTime extends GetTime
{
public void runCode()
{
for (int x=0;x<4000;x++ )
{
System.out.print(x);
}
}
}
class TemplateDemo
{
public static void main(String[] args)
{
SubTime st=new SubTime();
st.getTime();
}
}
6. 总结
模板方法设计模式:
在定义功能时,功能的一部分是确定的,但是有一部分是不确定的。
而确定的部分在使用不确定的部分,这时就将不确定的部分暴露出去,由该类的子类去完成。