当前位置: 移动技术网 > IT编程>开发语言>Java > Java设计模式之模板模式(Template模式)介绍

Java设计模式之模板模式(Template模式)介绍

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网