当前位置:
首页 >
模板设计模式,简单Java代码实现
发布时间:2025/3/20
28
豆豆
生活随笔
收集整理的这篇文章主要介绍了
模板设计模式,简单Java代码实现
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
/**模板设计模式:定义一个算法的骨架,而将具体的算法延迟到子类中进行实现* 优点:* 使用模板方法模式,在定义算法骨架的同时,可以很灵活地实现具体的算法,满足用户灵活多变的需求* 缺点:* 如果算法骨架有修改的话,则需要修改抽象类。*/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();//以下这些方法都可以调用方法来嵌套进去使用// 操作一// 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;}//定义为抽象方法让子类来实现public abstract void code() ;
}//子类实现父类方法
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* 模板设计模式:定义一个算法的骨架,而将具体的算法延迟到子类中进行实现* 优点:* 使用模板方法模式,在定义算法骨架的同时,可以很灵活地实现具体的算法,满足用户灵活多变的需求* 缺点:* 如果算法骨架有修改的话,则需要修改抽象类。* @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+"毫秒");*///使用模板设计模式后,就要新建一个类来将方法写进code()方法中Code c = new Code();long time = c.getTime();System.out.println(time);}
}
总结
以上是生活随笔为你收集整理的模板设计模式,简单Java代码实现的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 适配器设计模式,简单的Java代码模拟
- 下一篇: 《Java编程思想》《Think in