/**模板设计模式:定义一个算法的骨架,而将具体的算法延迟到子类中进行实现
* 优点:
* 使用模板方法模式,在定义算法骨架的同时,可以很灵活地实现具体的算法,满足用户灵活多变的需求
* 缺点:
* 如果算法骨架有修改的话,则需要修改抽象类。
*/
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 {
// 将需要运行的代码放进其中
@Override
public 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);
}
}