设计模式之Template(模版)
来源:互联网 发布:印度失业率数据 编辑:程序博客网 时间:2024/05/16 05:14
Template模板模式定义:
定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中.
使用Java的抽象类时,就经常会使用到Template模式,因此Template模式使用很普遍.而且很容易理解和使用。
public abstract class Benchmark
...{
/** *//**
* 下面操作是我们希望在子类中完成
*/
public abstract void benchmark();
/** *//**
* 重复执行benchmark次数
*/
public final long repeat (int count) ...{
if (count <= 0)
return 0;
else ...{
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++)
benchmark();
long stopTime = System.currentTimeMillis();
return stopTime - startTime;
}
}
}
...{
/** *//**
* 下面操作是我们希望在子类中完成
*/
public abstract void benchmark();
/** *//**
* 重复执行benchmark次数
*/
public final long repeat (int count) ...{
if (count <= 0)
return 0;
else ...{
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++)
benchmark();
long stopTime = System.currentTimeMillis();
return stopTime - startTime;
}
}
}
在上例中,我们希望重复执行benchmark()操作,但是对benchmark()的具体内容没有说明,而是延迟到其子类中描述:
public class MethodBenchmark extends Benchmark
...{
/** *//**
* 真正定义benchmark内容
*/
public void benchmark() ...{
for (int i = 0; i < Integer.MAX_VALUE; i++)...{
System.out.printtln("i="+i);
}
}
}
...{
/** *//**
* 真正定义benchmark内容
*/
public void benchmark() ...{
for (int i = 0; i < Integer.MAX_VALUE; i++)...{
System.out.printtln("i="+i);
}
}
}
至此,Template模式已经完成,是不是很简单?
我们称repeat方法为模板方法, 它其中的benchmark()实现被延迟到子类MethodBenchmark中实现了,
看看如何使用:
Benchmark operation = new MethodBenchmark();
long duration = operation.repeat(Integer.parseInt(args[0].trim()));
System.out.println("The operation took " + duration + " milliseconds");
long duration = operation.repeat(Integer.parseInt(args[0].trim()));
System.out.println("The operation took " + duration + " milliseconds");
也许你以前还疑惑抽象类有什么用,现在你应该彻底明白了吧? 至于这样做的好处,很显然啊,扩展性强,以后Benchmark内容变化,我只要再做一个继承子类就可以,不必修改其他应用代码.
- 设计模式之Template(模版)
- 模版(Template)设计模式
- [设计模式]Template模版模式
- 设计模式之template method模版方法模式
- [OOAD]设计模式之模版方法(Template Method)模式
- 设计模式读书笔记之模版方法模式(Template)
- 设计模式之(Template Method)模版方法模式
- 设计模式读书笔记之模版方法模式(Template)
- 【设计模式 - 23】之模版方法模式(Template)
- java设计模式之Template Method(模版方法)
- 设计模式之-模版方法(Template Method Design Pattern)
- 设计模式 - 模版方法模式 Template Method
- 设计模式:模版模式(Template Pattern)
- 设计模式:模版模式(Template Pattern)
- 设计模式:模版模式(Template Pattern)
- 设计模式:模版模式(Template Pattern)
- 设计模式:模版模式(Template Pattern)
- 设计模式:模版模式(Template Pattern)
- C++设计模式(来源:http://doc.readmen.com/13/126062.shtml)
- Java对象池技术原理及其实现
- VirtualBox桥接网络的配置
- GNU Free Documentation License
- Java里被遗忘的角落
- 设计模式之Template(模版)
- 再谈Java内存泄漏及代码完善
- [Java]JAVA获取相对路径问题的解决
- PE文件格式详解(上)
- (C#设计模式一)Singleton(单态)
- PE文件格式详解(下)
- Modal UpdateProgress的轻量级解决方案
- JRTPLIB库简介及应用(LIB文件编译方法 范例编译方法)
- 《錯過一時,錯過一生》