模板设计模式

package e.behavior_type_template_design_pattern;

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

/**
 * 模板设计模式: 1.计算for循环运行时间
 * 
 * @author Administrator
 * 
 * 模板设计模式概述:
 * 		模板方法模式就是定义一个算法的骨架
 * 		而将具体的算法延迟到子类中实现。
 * 		
 * 优点:
 * 		使用模板方法模式,在定义算法骨架的同时,
 * 		可以很灵活的实现具体的算法,满足用户灵
 * 		活多变的需求
 * 
 * 缺点:
 * 		如果算法骨架有修改的话,则需要修改抽象类
 */
public class TemplateDemo01 {
	public static void main(String[] args) throws Exception {
		GetTime get = new GetTime_();
		System.out.println(get.getTime() + "毫秒");
		// System.out.println(get.getTime_for() + "毫秒");

		// System.out.println(get.getTime_mv() + "毫秒");
	}
}

/*
 * 计算10000次for循环的用时
 */
abstract class GetTime {
	public long getTime() throws Exception {
		long start = System.currentTimeMillis();
		
		// 开闭原则:对扩展开放,对修改关闭
		// 这一段代码不确定;其它的代码是固定的
		code();
		
		long end = System.currentTimeMillis();
		
		return end - start;
	}
	
	// 将其中的code抽象出来,作为一个抽象类;
	// 需要子类去实现其中的抽象方法
	// 意思就是对扩展开放了,这就是模板
	public abstract void code();
	/*
	public long getTime_for() {
		long start = System.currentTimeMillis();
		for (int x = 0; x < 10000; x++) {
			System.out.println(x);
		}
		long end = System.currentTimeMillis();

		return end - start;
	}

	public long getTime_mv() throws Exception {
		long start = System.currentTimeMillis();
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream("a.avi"));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("b.avi"));
		byte[] bys = new byte[1024];
		int len = 0;
		while ((len = bis.read(bys)) != -1) {
			bos.write(bys, 0, len);
		}
		bos.close();
		bis.close();
		long end = System.currentTimeMillis();

		return end - start;
	}
	*/
}


class GetTime_ extends GetTime {

	@Override
	public void code() {
		for (int x = 0; x < 10000; x++) {
			// System.out.println(x);
		}
		long end = System.currentTimeMillis();
	}
	
}


原文地址:https://www.cnblogs.com/mzywucai/p/11053428.html