- package com.gao;
- /*
- * 需求:获取一段程序的运行时间
- * 原理:结束时间减去开始时间
- *
- * 获取时间:System.currentTimeMillis()
- *
- * 这个例子表示的就是模板方法设计模式
- *
- * 什么叫模板方法?
- * 在定义一个功能时有些部分是确定的,有些部分是不确定的,在确定的部分当中还包含不确定的部分,
- * 那么就要把不确定的部分暴露出去,让子类去实现这些不确定的部分
- * */
- abstract class GetTime
- {
- public final void getTime()
- {
- long start = System.currentTimeMillis();
- runCode();
- long end = System.currentTimeMillis();
-
- System.out.println("\n运行时间是" + (end - start) + "毫秒");
- }
- //不确定的部分定义为抽象方法
- public abstract void runCode();
- }
- class SubTime extends GetTime
- {
- @Override
- public void runCode()
- {
- for (int i = 0; i < 1000; i++)
- {
- System.out.print(i);
- }
- }
-
- }
- public class TemplateDemo
- {
- public static void main(String[] args)
- {
- SubTime st = new SubTime();
- st.getTime();
- }
- }
复制代码
|
|