---------------------- android培训、java培训、期待与您交流! ----------------------
/*
bxd 视频day07 11节,模板设计模式
需求:获取程序运行的时间。
*/
/*★
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();
}
}
---------------------------------------------------------------------------------
★*/
/*
封装方法,继承复写:
将要计算的程序代码封装成一个函数runCode()。
以后如果要再统计其他程序的运行时间,只需要将要运行的代码封装到runCode()方法中,并覆盖掉父类GetTime的对应方法就可以了。
可以定义runCode()方法为抽象方法,这样将GetTime类定义成abstract类。具体需要计算时间的代码交给子类去复写,获取时间这一功能交给父类去完成。
★
class GetTime
{
public void getTime()
{
long start = System.currentTimeMillis();
runCode();
//long end = System.currentTimeMillis();
//System.out.println("毫秒: "+(end-start));
System.out.println("毫秒: "+(System.currentTimeMillis()-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<200;x++)
{
System.out.print(x+" , ");
}
}
}
class TemplateDemo
{
public static void main(String[] args)
{
SubTime gt = new SubTime();
gt.getTime();
}
}
---------------------------------------------------------------------------------
★*/
/*
模板方法设计模式:
这种将不确定的功能定义为抽象,让子类去复写,父类只保留最基本的功能的模式。称之为模板方法设计模式。
注意:以下代码中,待执行的方法runCode()不一定要是抽象的。getTime()也不一定要定义成final,根据具体情况而已。
*/
abstract class GetTime
{
public final void getTime()//定义为final,是不想让这个类的唯一功能被复写。
{
long start = System.currentTimeMillis();
runCode();
long end = System.currentTimeMillis();
System.out.println("毫秒: "+(end-start));
}
public abstract void runCode();//定义为abstract,是不知道将来要运行的程序代码是什么。
}
class SubTime extends GetTime
{
public void runCode()
{
for(int x=0;x<1000;x++)
{
System.out.print(x+", ");
}
}
}
class TemplateDemo
{
public static void main(String[] args)
{
SubTime st = new SubTime();
st.getTime();
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------
详情请查看: