模版设计模式概述和使用
生活随笔
收集整理的這篇文章主要介紹了
模版设计模式概述和使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
模版設計模式概述
模版方法模式就是定義一個算法的骨架,而將具體的算法延遲到子類中來實現
優點
使用模版方法模式,在定義算法骨架的同時,可以很靈活的實現具體的算法,滿足用戶靈活多變的需求
缺點
如果算法骨架有修改的話,則需要修改抽象類
package cn.learn_01;public class ForDemo extends GetTime {@Overridepublic void code() {for (int x = 0; x < 100000; x++) {System.out.println(x);}}} package cn.learn_01;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;public abstract class GetTime {// 需求:請給我計算出一段代碼的運行時間public long getTime() {long start = System.currentTimeMillis();// for循環// for (int x = 0; x < 10000; x++) {// System.out.println(x);// }// 視頻// try {// BufferedInputStream bis = new BufferedInputStream(// new FileInputStream("a.avi"));// BufferedOutputStream bos = new BufferedOutputStream(// new FileOutputStream("b.avi"));// byte[] bys = new byte[1024];// int len = 0;// while ((len = bis.read(bys)) != -1) {// bos.write(bys, 0, len);// }// bos.close();// bis.close();// } catch (IOException e) {// e.printStackTrace();// }// 再給我測試一個代碼:集合操作的,多線程操作,常用API操作的等等...code();long end = System.currentTimeMillis();return end - start;}public abstract void code(); } package cn.learn_01;public class GetTimeDemo {public static void main(String[] args) {// GetTime gt = new GetTime();// System.out.println(gt.getTime() + "毫秒");GetTime gt = new ForDemo();System.out.println(gt.getTime() + "毫秒");gt = new IODemo();System.out.println(gt.getTime() + "毫秒");} } package cn.learn_01;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;public class IODemo extends GetTime{@Overridepublic void code() {try {BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.avi"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.avi"));byte[] bys = new byte[1024];int len = 0;while ((len = bis.read(bys)) != -1) {bos.write(bys, 0, len);}bos.close();bis.close();} catch (IOException e) {e.printStackTrace();}}}?
總結
以上是生活随笔為你收集整理的模版设计模式概述和使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 动态代理的概述和实现
- 下一篇: SpringMVC的XML配置解析