模块方法设计模式

来源:互联网 发布:大数据的书 编辑:程序博客网 时间:2024/06/05 07:11

需求:获取一段程序运行时间

原理:获取程序开始和结束的时间并相减即可

获取时间:System.currentTimeMillis();

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 p=new GetTime();p.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 Time 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));}}
。。。。省略了主函数


这样写是可以的,但我们发现只要重写for循环内容就行,所以把其封装,再重写

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 Time extends GetTime{public void runcode(){for(int x=0;x<4000;x++)System.out.print(x);}}//.....省略主函数;


但是问题又来了,但是如果在父类GetTime方法中,我们不知道runcode具体要运行什么代码;我们该怎么写;这时应该想到抽象继承;

abstract class GetTime{public void GetTime(){long start=System.currentTimeMillis();runcode();long end=System.currentTimeMillis();System.out.println("毫秒: "+(end-start));}public abstract void runcode();}class Time extends GetTime{public void runcode(){for(int x=0;x<4000;x++)System.out.print(x);}}class TemplateDemo{public static void main(String[] args){Time p=new Time();p.GetTime();}}

这样就OK了,记住使用继承抽象时,只能建立子类对象;

 

我们发现:

当代码完成优化后,就可以解决这类问题;

这种方式,就叫模板方法设计模式。

什么是模板方法??

在定义功能是,功能的一部分是确定的,但是有一部分是非确定的,而确定的部分在使用不确定的部分,那么这时就将不确定的部分暴露出去,有给类的子类去完成

 

 

 

 

 

1 0