模板方法模式 屬於行為型模式。它在一個抽象類中定義一個算法的框架(模板方法),將某些具體步驟的實現延遲到子類中。這使得子類可以在不改變算法結構的情況下,重新定義算法的某些步驟。
// 抽象類:定義算法骨架
public abstract class Benchmark {
// 基本操作:由子類實現具體測試邏輯
public abstract void benchmark();
// 模板方法:final 防止被覆寫,封裝算法流程
public final long repeat(int count) {
if (count <= 0) return 0;
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
benchmark(); // 呼叫基本操作
}
long stopTime = System.currentTimeMillis();
return stopTime - startTime; // 返回總耗時
}
}
// 具體子類:實現具體測試內容
public class MethodBenchmark extends Benchmark {
@Override
public void benchmark() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
System.out.println("i=" + i); // 模擬耗時操作
}
}
}
// 客戶端調用
public class Client {
public static void main(String[] args) {
Benchmark operation = new MethodBenchmark();
long duration = operation.repeat(10); // 執行 10 次
System.out.println("操作耗時:" + duration + " 毫秒");
}
}
java.util.AbstractList、java.io.InputStream、javax.servlet.http.HttpServlet 等大量使用了模板方法模式。