Java design pattern: template method pattern or template design pattern (behavior pattern), java Design Pattern
Abstract class, the unchanged code is written, and the part to be changed is left to the subclass for implementation:
Package behavior _ template method mode; // template design mode means to write the unchanged positioning part, and leave the changed part to the subclass to implement public abstract class GetTime {public long getTime () throws Exception {long start = System. currentTimeMillis (); // start time/* // for Loop for (int I = 0; I <10000; I ++) {System. out. println (I);} * // video/design mode/src/avi/. aviBufferedInputStream input = new BufferedInputStream (new FileInputStream ("/design mode/src/avi/. avi "); BufferedOutputStream output = new BufferedOutputStr Eam (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 (); // test the code again: multi-threaded operations for Set Operations and common APIs. Do you need to write code, trouble !!!!!!!!!!!!!!!! */Code (); // subclass to write long end = System. currentTimeMillis (); // return end-start at the end time;} // write an abstract method. The subclass implements the specific operation (content) of the method. public abstract void code (); // left to subclass Implementation}
For Loop running time class:
Package behavior _ template method mode; public class ForGetTime extends GetTime {@ Overridepublic void code () {for (int I = 0; I <10000; I ++) {System. out. println (I );}}}
Class for IO stream to read the video and request its running time:
Package behavior _ template method mode; 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/. avi "); BufferedOutputStream output = new BufferedOutputStream (new File OutputStream ("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 ();}}}
Test class:
Package behavior _ template method mode; public class GetTimeMain {public static void main (String [] args) throws Exception {// GetTime gTime = new GetTime (); // System. out. println (gTime. getTime () + "millisecond"); // GetTime gt = new ForGetTime (); System. out. println (gt. getTime () + "millisecond"); // The value is re-assigned to read the IO stream. avimpaired = new IOGetTime (); System. out. println (gt. getTime () + "millisecond ");}}