首页
论坛
图书
开发资料
在线文档
网址
下载
联系我们
 新闻│Java│JavaScript│Eclipse│Eclipse 英文│J2EE│J2ME│J2SE│JSP│Netbeans│Hibernate│JBuilder│Spring│Struts
站内搜索: 请输入搜索关键词

当前页面: 开发资料首页 → Java 专题 → 设计模式之Template

设计模式之Template

摘要: 设计模式之Template

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle">

<table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="684" height="20"> </td> </tr> </table>

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

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

<table cellSpacing=3 cellPadding=3 width="80%" border=0> <tr> <td bgColor=#cccccc>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;
   }
}
}

</td> </tr> </table>

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

<table cellSpacing=3 cellPadding=3 width="80%" border=0> <tr> <td bgColor=#cccccc>public class MethodBenchmark extends Benchmark
{
   /**
   * 真正定义benchmark内容
   */
   public void benchmark() {

     for (int i = 0; i < Integer.MAX_VALUE; i++){
       System.out.printtln("i="+i);    
    }
   }
}
</td> </tr> </table>

至此,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");

也许你以前还疑惑抽象类有什么用,现在你应该彻底明白了吧? 至于这样做的好处,很显然啊,扩展性强,以后Benchmark内容变化,我只要再做一个继承子类就可以,不必修改其他应用代码.

</td> </tr> <tr>


↑返回目录
前一篇: 有关有效使用final关键字的准则
后一篇: DAO 设计模式经典实例

首页 | 全站 Sitemap | 联系我们 | 设为首页 | 收藏本站
版权所有 Copyright © 2006-2007, Java 编程资料牛鼻站, All rights reserved