模版方法模式是设计模式中行为型模式的一种
模版方法模式就是定义一个算法的骨架
而将具体的算法延迟到子类中实现
优点与缺点
优点 :
使用模版方法模式,在定义算法骨架的同时
可以很灵活的实现具体的算法,满足用户灵活多变的需求
缺点 :
如果算法骨架有修改,则需要修改具体抽象类
简单案例
实现一个计时类,能获取执行任意一段代码所花费的时间
那么需要在代码执行前记录一下时间
运行代码
在代码执行后记录一下时间
获取时间的差值
具体实现如下 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| public abstract class TemplateMethod { public abstract void code(); public long getRuntime(){ long start = System.currentTimeMillis(); code(); long end = System.currentTimeMillis(); return end - start; } } public static void main(String[] args) { TemplateMethod t = new TemplateMethod() { @Override public void code() { testFor(); } }; System.out.println(t.getRuntime()+"毫秒"); t = new TemplateMethod() { @Override public void code() { copyAvi(); } }; System.out.println(t.getRuntime()+"毫秒"); } public static void testFor() { for (int i = 0; i < 10000; i++) System.out.println(i); } public static void copyAvi() { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream("a.avi")); out = new BufferedOutputStream(new FileOutputStream("copy.avi")); byte[] bytes = new byte[1024]; int len; while ((len = in.read(bytes)) != -1) { out.write(bytes, 0, len); out.flush(); } }catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); } } }
|
可以看到,只需要创建对应的子类即可灵活的套用骨架
运行结果如下 :
