Java設計模式之模板方法模式或者說模板設計模式(屬於行為型),java設計模式
抽象類別,不變的代碼寫了,要變化的部分留給子類去實現:
package 行為型_模板方法模式;//模板設計模式的意思是把不變定位部分寫出來,變化的部分留給子類去實現public abstract class GetTime {public long getTime() throws Exception{long start = System.currentTimeMillis();//開始時間/*//for迴圈for(int i=0;i<10000;i++){System.out.println(i);}*//*//視頻 /設計模式/src/avi/a.aviBufferedInputStream input= new BufferedInputStream(new FileInputStream("/設計模式/src/avi/a.avi"));BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("b.avi"));byte[] b = new byte[1024];int len=0;while((len=input.read(b))!=-1){output.write(b,0,len);}output.close();input.close();//再給我測試一個代碼:集合操作的多線程操作,常用API,那麼你也還要寫代碼嗎,麻煩!!!!!!!!!!!!!!!!*/code();//子類去寫long end = System.currentTimeMillis();//結束時間return end-start;}//寫一個抽象的方法,子類自己去實現方法的具體操作(內容)public abstract void code();//留給子類實現}
For迴圈求已耗用時間類:
package 行為型_模板方法模式;public class ForGetTime extends GetTime{@Overridepublic void code() {for(int i=0;i<10000;i++){System.out.println(i);}}}
IO流讀取視頻,求其已耗用時間的類:
package 行為型_模板方法模式;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class IOGetTime extends GetTime{@Overridepublic void code(){try {BufferedInputStream input = new BufferedInputStream(new FileInputStream("avi/a.avi"));BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream("b.avi"));byte[] b = new byte[1024];int len=0;while((len=input.read(b))!=-1){output.write(b,0,len);}output.close();input.close();} catch (IOException e) {e.printStackTrace();}}}
測試類別:
package 行為型_模板方法模式;public class GetTimeMain {public static void main(String[] args) throws Exception {//GetTime gTime = new GetTime();//System.out.println(gTime.getTime()+"毫秒");//面向抽象編程GetTime gt = new ForGetTime();System.out.println(gt.getTime()+"毫秒");//重新賦值為讀取的是IO流.avigt = new IOGetTime();System.out.println(gt.getTime()+"毫秒");}}