模板设计模式

模板设计模式

模板设计模式概述

模板方法模式就是定义一个算法的骨架,而将具体的算法延迟到子类中来实现

优点

使用模板方法模式,在定义算法骨架的同时,可以很灵活的实现具体的算法,满足用户灵活多变的需求

缺点

如果算法骨架有修改的话,则需要修改抽象类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 模板设计模式
 * */

public class Test {
	public static void main(String[] args) throws Exception {
		GetTime gt1 = new ForDemo();
		System.out.println(gt1.getTime() + "毫秒");

		GetTime gt2 = new IODemo();
		System.out.println(gt2.getTime() + "毫秒");
	}
}

abstract class GetTime {
	public long getTime() {
		long start = System.currentTimeMillis();

		code();

		long end = System.currentTimeMillis();

		return end - start;
	}

	public abstract void code();
}

class ForDemo extends GetTime {
	public void code() {
		for (int i = 0; i < 100000; i++) {
			System.out.println(i);
		}
	}
}

class IODemo extends GetTime {
	public void code() {
		try {
			BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\zikao\20151130054234629.xls"));
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream("E:\zikao\new_20151130054234629.xls"));
			byte bys[] = new byte[1024];
			int len = 0;
			while ((len = bis.read(bys)) != -1) {
				bos.write(bys, 0, len);
			}
			bos.close();
			bis.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
原文地址:https://www.cnblogs.com/denggelin/p/6358324.html