2008-05-14

JFreeChart中应用Template模式

关键字: jfreechart template 模式

今天在看Spring对JDBC的封装,其中提到了JDBCTemplate,所以想起了Template模式,这个模式,以前看过,但是没有有过,并且已经是老长时间以前的事了,大部分已经忘了。在网上收了一下,找了篇Jdon上关于Template模式的文章,重温了一下这个模式。

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;
  }
}
}


 

在上例中,我们希望重复执行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模式已经完成,是不是很简单?

我们称repeat方法为模板方法, 它其中的benchmark()实现被延迟到子类MethodBenchmark中实现了,

看看如何使用:

Benchmark operation = new MethodBenchmark();
long duration = operation.repeat(Integer.parseInt(args[0].trim()));
System.out.println("The operation took " + duration + " milliseconds");

 在使用JFreeChart中,产生chart的步骤是固定的,而数据集和产生的chart对象是不确定的,因此可以使用Template简化Chart的创建过程.

 

评论
发表评论

您还没有登录,请登录后发表评论

hintcnuie
搜索本博客
我的相册
90f50603-7a67-3b98-9e1a-d6ec48edb2f5-thumb
facebook application break down
共 5 张
最近加入圈子
存档
最新评论