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()+"毫秒");}}

人总是珍惜未得到的,而遗忘了所拥有的

Java设计模式之模板方法模式或者说模板设计模式(属于行为型)

相关文章:

你感兴趣的文章:

标签云: