黑马程序员技术交流社区

标题: 模板设计模式 [打印本页]

作者: 愚翁    时间: 2015-7-13 09:24
标题: 模板设计模式
  获取时间的代码,用到的就是模板方法设计模式,就是在定义功能时,功能的一部分是确定的,但是有一部分是不确定的,那而确定的部分在使用不确定的部分,那么这时就将不确定的部分暴露(不一定抽象化)出去,让子类去完成。代码实现如下所示:
  public class Test
{
public static void main(String args[])
{
  SubTime sb = new SubTime();
  sb.getTime();
  
}

}
abstract class GettTime
{
public final void getTime() //此功能不允许被复写,因为它是此类的主要功能
{
  long t1 = System.currentTimeMillis();
  runcode();
  long t2 = System.currentTimeMillis();
  System.out.println("毫秒:" + (t2 - t1));
}
public abstract void runcode(); //不确定的方法暴露出去,不一定要抽象化,如我有默认的实现
}
class SubTime extends GetTime
{
public void runcode()
{
  for(int x = 0 ;  x < 4000 ; x++)
  {
   System.out.print(x);
  }
}
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2