---
title: "Template模式"
author: "Jameslyy"
date: "2007-08-20T13:56:58Z"
tags: []
slug: "template"
draft: false
lastmod: "2007-08-20T13:56:58Z"
id: 114337
url: "https://jamesblog.iteye.com/blog/114337"
---

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

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

public abstract class Benchmark {  
　　/\**  
　　* 下面操作是我们希望在子类中完成  
　　\*/  
　　public abstract void benchmark();

　　/\**  
　　* 重复执行benchmark次数  
　　\*/  
　　public final long repeat (int count) {  
　　　　if (count &lt;= 0)  
　　　　　　return 0;  
　　　　else {  
　　　　　　long startTime = System.currentTimeMillis();

　　　　        for (int i = 0; i &lt; 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 &lt; Integer.MAX\_VALUE; i++){  
　　　 　　System.out.printtln("i="+i);　 　　  
　　　 }  
　　}  
}

Template模式提高了程序的可扩展性。

引自[http://www.jdon.com/designpatterns/template.htm](http://www.jdon.com/designpatterns/template.htm)