Java设计模式-5.模板模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cmm0401/article/details/82973600

模板模式

1、模版模式概述

  • 模版设计模式,就是定义一个算法的骨架,而将具体的算法延迟到子类中来实现。
  • 优点:使用模板设计模式,在定义算法骨架的同时,可以很灵活的实现具体的不同算法,满足用户灵活多变的需求。
  • 缺点:如果算法骨架有修改的话,则需要修改抽象类。

2、模板模式举例

  需求:计算出一段代码的运行时间。

(1)模板模式类:GetTime.java

package cn.itcast_01;
public abstract class GetTime {
	// 需求:请给我计算出一段代码的运行时间
	public long getTime() {
		long start = System.currentTimeMillis();
		// for循环
		// 视频
		// 再给我测试一个代码:集合操作的,多线程操作,常用API操作的等等...
		code();
		long end = System.currentTimeMillis();
		return end - start;
	}
	public abstract void code();
}

(2)for循环的时间

package cn.itcast_01;
public class ForDemo extends GetTime {
	@Override
	public void code() {
		for (int x = 0; x < 100000; x++) {
			System.out.println(x);
		}
	}
}

(3)复制视频的时间

package cn.itcast_01;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IODemo extends GetTime{
	@Override
	public void code() {
		try {
			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();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

(4)模板测试类:GetTimeDemo.java

package cn.itcast_01;
public class GetTimeDemo {
	public static void main(String[] args) {
		GetTime gt = new ForDemo();
		System.out.println(gt.getTime() + "毫秒");
		gt = new IODemo();
		System.out.println(gt.getTime() + "毫秒");
	}
}

猜你喜欢

转载自blog.csdn.net/cmm0401/article/details/82973600