My FAQ,最新最全的IT技术FAQ
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 未整理篇 | 技术讨论
  当前位置: > 程序开发 > 编程语言 > Java > 设计模式
设计模式袖珍版 连续转载之 - Template
作者:未知 时间:2005-07-24 21:24 出处:JR 责编:My FAQ
              摘要:设计模式袖珍版 连续转载之 - Template
原作:fanix

Template定义:
定义一个操作中算法的骨架,将一些步骤的执行延迟到其子类中.

使用Java的抽象类时,就经常会使用到Template模式,因此Template模式使用很普遍.而且很容易理解和使用。

程序代码:

  1. public abstract class Benchmark
  2. {
  3.   /**
  4.   * 下面操作是我们希望在子类中完成
  5.   */
  6.   public abstract void benchmark(); 
  7.   /**
  8.   * 重复执行benchmark次数
  9.   */
  10.   public final long repeat (int count) {
  11.     if (count <= 0)
  12.       return 0;
  13.     else {
  14.       long startTime = java/lang/System.java.html" target="_blank">System.currentTimeMillis();
  15.     for (int i = 0; i < count; i++) 
  16.       benchmark();
  17.     long stopTime = java/lang/System.java.html" target="_blank">System.currentTimeMillis();
  18.     return stopTime - startTime;
  19.   }
  20. }
  21. }

 

在上例中,我们希望重复执行benchmark()操作,但是对benchmark()的具体内容没有说明,而是延迟到其子类中描述:
程序代码:

  1. public class MethodBenchmark extends Benchmark
  2. {
  3.   /**
  4.   * 真正定义benchmark内容
  5.   */
  6.   public void benchmark() {
  7.     for (int i = 0; i < java/lang/Integer.