`
dev_liu
  • 浏览: 109343 次
  • 性别: Icon_minigender_1
  • 来自: 成都
最近访客 更多访客>>
社区版块
存档分类
最新评论

设计模式之Template

阅读更多

Template 定义:
定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中.
其实Java 的抽象类本来就是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;
}
}
}
在上例中,我们希望重复执行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);
}
}
}
至此,Template 模式已经完成,是不是很简单?看看如何使用:
Benchmark operation = new MethodBenchmark();
long duration = operation.repeat(Integer.parseInt(args[0].trim()));
System.out.println("The operation took " + duration + " milliseconds");
也许你以前还疑惑抽象类有什么用,现在你应该彻底明白了吧? 至于这样做的好处,很显然
啊,扩展性强,以后Benchmark 内容变化,我只要再做一个继承子类就可以,不必修改其他应
用代码.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics