Java设计模式(13)模板模式(Template模式)

时间:2021-11-30 17:12:52

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内容变化,我只要再做一个继承子类就可以,不必修改其他应用代码。

系列文章:

Java设计模式(1)工厂模式(Factory模式)

Java设计模式(2)单态模式(Singleton模式)

Java设计模式(3)建造者模式(Builder模式)

Java设计模式(4)原型模式(Prototype模式)

Java设计模式(5)共享模式/享元模式(Flyweight模式)

Java设计模式(6)桥模式(Bridge模式)

Java设计模式(7)装饰模式(Decorator模式)

Java设计模式(8)组合模式(Composite模式)

Java设计模式(9)适配器模式(Adapter模式)

Java设计模式(10)代理模式(Proxy模式)

Java设计模式(11)外观模式(Facade模式)

Java设计模式(12)迭代模式(Iterator模式)

Java设计模式(13)模板模式(Template模式)

Java设计模式(14)责任链模式(Chain of Responsibility模式)

Java设计模式(15)备忘录模式(Memento模式)

Java设计模式(16)中介模式(Mediator模式)

Java设计模式(17)解释器模式(Interpreter模式)

Java设计模式(18)策略模式(Strategy模式)

Java设计模式(19)状态模式(State模式)

Java设计模式(20)观察者模式(Observer模式)

Java设计模式(21)访问模式(Visitor者模式)

Java设计模式(22)命令模式(Command模式)