需求: 请给设计一个类, 可以计算出一段代码的运行时间
不使用模板设计
import java.io.*; public class GetTime { public long getTime() { long start = System.currentTimeMillis(); // 第一次: 测试for循环代码时间 /* for (int i = 0; i < 10000; i++) { System.out.println(i); } */ // 第二次: 测试复制视频代码时间 try { BufferedInputStream bis = new BufferedInputStream(new FileInputStream("day27_Pattern/src/com/itcast_01/a.mp4")); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day27_Pattern/src/com/itcast_01/b.mp4")); byte[] bytes = new byte[1024]; int len = 0; while ((len = bis.read(bytes)) != -1) { bos.write(bytes, 0, len); } bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); return end - start; } } public class GetTimeDemo { public static void main(String[] args) { GetTime gt = new GetTime(); System.out.println(gt.getTime() + "毫秒"); } }缺点: 我每次想写的功能都不一样, 每一次测试代码, 必须要把之前写的代码注释掉. 再次强调开闭原则, 对扩展开放, 对修改关闭. 所以我们用模板设置模式来做一遍.
模板设计模式 import java.io.*; public abstract class GetTime { // 需求:请给我计算一段代码的运行时间 public long getTime() { long start = System.currentTimeMillis(); code(); long end = System.currentTimeMillis(); return end - start; } public abstract void code(); } 继承GetTime, 专门写要测试的功能即可 public class ForDemo extends GetTime { @Override public void code() { for (int i = 0; i < 1000; i++) { System.out.println(i); } } } 测试类 public class GetTimeDemo { public static void main(String[] args) { GetTime gt = new ForDemo(); System.out.println(gt.getTime() + "毫秒!"); } }