模板设计模式:
含义:父类统一事情步骤,父类定义抽象方法既是(钩子方法),其中细节由子类实现。第三方调用父类接口。
例子: GetTimeTemplate定义固定的时间计算方式 :code()方法为真正操作,每个子类实现不一样。
public abstract class GetTimeTemplate {
// 固定流程方法
public long getTime() {
// 获取起始时间
long t1 = System.currentTimeMillis();
// 模板方法
code();
// 获取结束时间
long t2 = System.currentTimeMillis();
return t2 - t1;
}
// 钩子方法 交给子类实现
public abstract void code();
}
复制文件子类:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import template.father.GetTimeTemplate;
public class CopyFileDemo extends GetTimeTemplate {
@Override
public void code() {
//复制文件
try {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("张三.jpg"));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream("mn.jpg"));
byte[] bs = new byte[256];
int len = 0;
while((len = inputStream.read(bs)) != -1){
outputStream.write(bs, 0, len);
outputStream.flush();
}
//释放资源
inputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
for循环子类:
import template.father.GetTimeTemplate;
public class ForDemo extends GetTimeTemplate{
@Override
public void code() {
//输出for循环
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
}
}
调用时使用具体实现:
public class TemplateTest {
public static void main(String[] args) {
/*GetTime time = new GetTime();
System.out.println("耗时 "+time.getTime()+" 毫秒");*/
GetTimeTemplate time = new ForDemo();
System.out.println("耗时 "+time.getTime()+" 毫秒");
GetTimeTemplate time2 = new CopyFileDemo();
System.out.println("耗时 "+time2.getTime()+" 毫秒");
}
}