模板设计模式,简单Java代码实现
生活随笔
收集整理的這篇文章主要介紹了
模板设计模式,简单Java代码实现
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/**模板設(shè)計模式:定義一個算法的骨架,而將具體的算法延遲到子類中進行實現(xiàn)* 優(yōu)點:* 使用模板方法模式,在定義算法骨架的同時,可以很靈活地實現(xiàn)具體的算法,滿足用戶靈活多變的需求* 缺點:* 如果算法骨架有修改的話,則需要修改抽象類。*/package july.star.template;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/*** GetTime** @author MoXingJian* @email 939697374@qq.com* @date 2016年12月11日 下午5:35:40* @version 1.0*/
public abstract class GetTime {public long getTime() {long start = System.currentTimeMillis();//以下這些方法都可以調(diào)用方法來嵌套進去使用// 操作一// for (int i = 0; i <= 10000; i++) {// System.out.println(i);// }// 操作二/*try {BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.txt"));byte[] bys = new byte[1024];int len = 0;while((len = bis.read(bys)) != -1){bos.write(bys, 0, len);bos.flush();}bos.close();bis.close();} catch (Exception e) {e.printStackTrace();}*/// 諸如此類的方法。。。。code(); //用于存放以上的方法的代碼long end = System.currentTimeMillis();return end - start;}//定義為抽象方法讓子類來實現(xiàn)public abstract void code() ;
}//子類實現(xiàn)父類方法
package july.star.template;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/*** Code** @author MoXingJian* @email 939697374@qq.com* @date 2016年12月11日 下午5:56:55* @version 1.0*/
public class Code extends GetTime {// 將需要運行的代碼放進其中@Overridepublic void code() {// 操作一/** for (int i = 0; i <= 10000; i++) { System.out.println(i); }*/// 操作二try {BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.txt"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.txt"));byte[] bys = new byte[1024];int len = 0;while ((len = bis.read(bys)) != -1) {bos.write(bys, 0, len);bos.flush();}bos.close();bis.close();} catch (Exception e) {e.printStackTrace();}}
}//測試
package july.star.template;/*** GetTimeDemo* 模板設(shè)計模式:定義一個算法的骨架,而將具體的算法延遲到子類中進行實現(xiàn)* 優(yōu)點:* 使用模板方法模式,在定義算法骨架的同時,可以很靈活地實現(xiàn)具體的算法,滿足用戶靈活多變的需求* 缺點:* 如果算法骨架有修改的話,則需要修改抽象類。* @author MoXingJian* @email 939697374@qq.com* @date 2016年12月11日 下午5:37:46* @version 1.0*/
public class GetTimeDemo {public static void main(String[] args) {//使用前/*GetTime gt = new GetTime();long time = gt.getTime();System.out.println(time+"毫秒");*///使用模板設(shè)計模式后,就要新建一個類來將方法寫進code()方法中Code c = new Code();long time = c.getTime();System.out.println(time);}
}
總結(jié)
以上是生活随笔為你收集整理的模板设计模式,简单Java代码实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 适配器设计模式,简单的Java代码模拟
- 下一篇: 《Java编程思想》《Think in