# 模板方法模式

模板方法模式是一种行为[设计模式](https://www.edgepedia.org/zh/design-patterns)，在这种模式中，基类将算法的骨架定义为单个方法，把某些步骤推迟到子类中，由子类重写这些步骤，而不改变算法的整体结构。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup> 四人组——埃里希·伽玛（Erich Gamma）、理查德·赫尔姆（Richard Helm）、拉尔夫·约翰逊（Ralph Johnson）和约翰·弗利赛德斯（John Vlissides）——在1994年的模式目录中将其定义为：“在一个操作中定义算法的骨架，将某些步骤推迟到子类中。模板方法让子类重新定义算法的某些步骤，而不改变算法的结构。”<sup>[2](https://www.acronos.com/DesignPatterns/template-method.html)</sup>

| 关键事实 | 详情 |
|---|---|
| 类别 | 行为模式，也是GoF目录中两种行为*类*模式之一，书中称其为两者中更简单、更常见的一种<sup>[3](https://www.oreilly.com/library/view/design-patterns-elements/0201633612/ch05.html)</sup> |
| 机制 | 抽象类中的一个具体模板方法按固定顺序调用一系列步骤，其中有些是抽象步骤，有些带有默认实现，有些是空钩子<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup> |
| 变化机制 | 继承：子类重写步骤，但不重写模板方法本身，模板方法通常被声明为final<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup> |
| 最接近的替代方案 | 策略模式，基于组合，允许在运行时改变行为；模板方法在类设计时即已固定<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup> |
| 框架角色 | 框架控制反转背后的机制：框架的骨架调用应用代码，而非反过来<sup>[4](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup> |
| Java示例 | `java.io.InputStream`、`OutputStream`、`Reader`和`Writer`的非抽象方法；`AbstractList`、`AbstractSet`和`AbstractMap`；`HttpServlet`的`doXXX()`方法<sup>[5](https://refactoring.guru/design-patterns/template-method/java/example)</sup> |

## 工作原理

该模式将算法分解为一系列步骤，把每个步骤变成一个方法，并将对这些方法的调用放在抽象类中的单个模板方法内。步骤分为三种。抽象步骤必须由每个子类实现。可选步骤在基类中有默认实现，可以被重写。钩子是方法体为空的可选步骤；即使钩子从未被重写，模板方法也能正确运行，钩子通常放在关键步骤之前和之后，为子类提供扩展点。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup>

具体类可以重写步骤，但不能重写模板方法本身。实现中通常将模板方法标记为`final`，使子类无法重新排列顺序。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup> 这一限制正是该模式的关键所在，而非缺陷：流程的顺序只写一次，写在一个地方，而变化的部分则留作空洞，由子类填充。<sup>[2](https://www.acronos.com/DesignPatterns/template-method.html)</sup>

第二个好处是去重。当多个类包含几乎相同、仅有细微差别的算法时，可以将共享步骤上提到超类中，而将变化的代码留在子类中；执行这一操作的refactoring本身被称为“形成模板方法”，而形成模板方法是开闭原则的一种应用，因为新的算法变体只需要一个新的子类。<sup>[6](https://refactoring.guru/form-template-method)</sup>

## 起源

该模式出现在《设计模式：可复用面向对象软件的基础》一书中，该书由Addison-Wesley于1994年10月31日出版，作者为伽玛、赫尔姆、约翰逊和弗利赛德斯，书中收录了23种模式，后来被称为GoF书。<sup>[7](https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-software-9780201633610)</sup> 在行为模式章节中，模板方法是两种行为类模式之一，这意味着它通过继承在类之间分配行为，而非在对象之间分配行为，该书的章节正文称其为两者中更简单、更常见的一种。<sup>[3](https://www.oreilly.com/library/view/design-patterns-elements/0201633612/ch05.html)</sup>

其底层机制早于这个名称。马丁·福勒（Martin Fowler）是一位以企业软件设计写作闻名的英国软件工程师，他将“控制反转”一词追溯到拉尔夫·约翰逊和布莱恩·富特（Brian Foote）1988年的论文《设计可复用类》，并引用模板方法作为一个直接的例子：超类定义控制流，子类通过重写或实现方法来扩展它。<sup>[4](https://www.martinfowler.com/bliki/InversionOfControl.html)</sup> GoF书本身指出，模板方法导致控制反转，即父类调用子类的操作，而非反过来，这正是框架与工具包的区别所在：使用工具包时，你调用可复用代码；使用框架时，你编写框架调用的代码。<sup>[8](https://citeseerx.ist.psu.edu/document?doi=4619b65fe1aa3a868e56b14c796b29118df82f4d&repid=rep1&type=pdf)</sup>

## 模板方法与策略模式

模板方法和策略模式都使算法的一部分行为可互换，它们是同一问题的两种标准答案，这就是它们经常被比较的原因。<sup>[9](https://takt.dev/design-pattern/advanced/comparisons/strategy-template)</sup> 区别在于机制和控制流的归属：

- **模板方法**使用继承。基类拥有顺序，并调用子类的步骤；变化在类层次结构设计时即已固定，客户端必须定义类并创建子类才能参与。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup><sup> • </sup><sup>[9](https://takt.dev/design-pattern/advanced/comparisons/strategy-template)</sup>
- **策略模式**使用组合。整个算法封装在一个单独的对象中，由上下文委托给它，并且可以通过传入不同的策略对象在运行时替换。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup>

选择取决于需要变化的是什么。如果整体流程必须保持固定，只有个别步骤不同，模板方法在编译时强制执行这一约束：子类实际上无法重写规定步骤顺序的方法。如果行为必须在运行时切换，或者多个独立方面同时变化，策略模式更合适。<sup>[9](https://takt.dev/design-pattern/advanced/comparisons/strategy-template)</sup><sup> • </sup><sup>[10](https://www.systemoverflow.com/learn/behavioral-patterns/template-method-pattern/template-method-vs-alternatives-when-to-use-each)</sup> 两者也能很好地结合：一个数据导出系统可以用模板方法实现其固定的提取、转换和加载顺序，同时在转换步骤内部用策略模式替换转换算法。<sup>[10](https://www.systemoverflow.com/learn/behavioral-patterns/template-method-pattern/template-method-vs-alternatives-when-to-use-each)</sup>

其他模式与它直接相关。工厂方法是模板方法的一种特化，工厂方法经常作为更大模板方法中的一个步骤，实践中大多数工厂方法正是出现在这里。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup><sup> • </sup><sup>[2](https://www.acronos.com/DesignPatterns/template-method.html)</sup>

## 实践中的应用

该模式在框架中最为常见，应用代码是他人流程中的乘客。<sup>[11](https://javascriptcodex.com/template-method/)</sup> 有文档记载的例子包括：

- **Java标准库。** `java.io.InputStream`、`OutputStream`、`Reader`和`Writer`，以及`AbstractList`、`AbstractSet`和`AbstractMap`的所有非抽象方法，都是调用抽象或可重写步骤的模板方法。在`javax.servlet.http.HttpServlet`中，每个`doXXX()`方法默认发送HTTP 405“方法不允许”，并意图被重写。<sup>[5](https://refactoring.guru/design-patterns/template-method/java/example)</sup> `AbstractList`对形态说得很明确：要实现一个不可修改的列表，程序员扩展该类并只提供`get(int)`和`size()`，而该类在这些方法之上实现迭代器和其他操作。<sup>[12](https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/util/AbstractList.html)</sup>
- **JUnit。** 经典的`TestCase.runBare()`方法调用`setUp()`，在try块中运行测试，并在finally块中调用`tearDown()`；这两个空的protected方法是钩子，由每个测试子类填充。<sup>[13](https://martinfowler.com/bliki/CallSuper.html)</sup>
- **Spring。** `JdbcTemplate`处理连接的打开和关闭、语句的准备和执行、结果迭代以及异常转换，而应用代码提供SQL并通过回调接口（如`PreparedStatementCreator`和`RowCallbackHandler`）提取结果。<sup>[14](https://docs.spring.io/spring-framework/reference/data-access/jdbc/core.html)</sup>

该模式还修正了一个常见的框架坏味道。在“调用超类”反模式中，文档告诉子类编写者重写某个方法，但要记得在开头调用超类；福勒认为，每当你必须记得每次都做某件事时，这就是糟糕API的标志，通常的补救方法是将该方法转换为模板方法，并提供一个单独的钩子供子类重写。<sup>[13](https://martinfowler.com/bliki/CallSuper.html)</sup>

## 局限与批评

GoF风格的代价在标准论述中说得直白：某些客户端可能受所提供的骨架限制，抑制默认步骤实现的子类可能违反里氏替换原则，而且随着步骤数量增长，模板方法变得难以维护。<sup>[1](https://refactoring.guru/design-patterns/template-method)</sup> 更根本的问题是脆弱基类：子类的正确性不仅依赖于父类声明的成员，还依赖于父类调用它的时机以及父类在那些时刻所持有的状态——这些在任何签名中都不可见——因此仅仅交换模板方法中两个步骤的顺序，虽然算作源码兼容的更改，却可能破坏每个子类，甚至包括你不拥有的代码中的子类。<sup>[2](https://www.acronos.com/DesignPatterns/template-method.html)</sup>

现代设计建议通常更倾向于策略模式，体现为“优先使用组合而非继承”的原则，并列出完全不应使用模板方法的情况：当步骤顺序本身在不同变体之间变化时，当必须混合来自不同层次结构的步骤时，当继承层次结构已经达到三层或更深时，或者当算法只有一个可变步骤时——此时单个策略注入比抽象类更简单。<sup>[15](https://www.designpatternsinaction.com/pattern/template-method)</sup> 在具有一等函数的语言中，该模式通常消解为一个接收可变步骤作为回调的函数，这在机制上是相同的想法，但所需的辅助结构更少，也没有脆弱基类问题。<sup>[11](https://javascriptcodex.com/template-method/)</sup>

实证结果好坏参半，而非一致有利。一项对50万行C++商业产品为期三年的研究发现，不同设计模式之间的缺陷率存在显著差异，从平均率的63%到154%不等，但模板方法模式在简单和复杂情况下都被使用，导致两个方向都没有明显趋势。<sup>[16](https://www.researchgate.net/publication/3188469_Defect_frequency_and_design_patterns_an_empirical_study_of_industrial_code)</sup> 另一项关于模式角色的实证研究发现，钩子类变化更频繁，而模板类和实现类变化较少，并且在控制类大小后，模式角色除了对类大小的影响外，几乎没有额外的解释力。<sup>[17](https://link.springer.com/article/10.1007/s10664-010-9148-2)</sup>

保留它的反驳论点是：关于组合的标准建议是关于复用实现的建议，而模板方法做的是不同的事情：它定义了一个协议。当顺序是一条不可更改的规则时，基类中的密封方法将该约束编码到类型系统中，这是任何策略对象都无法表达的；这样做的成本也更低，不需要额外的对象或接口，而且可变步骤保留了对基类protected成员的访问权。<sup>[2](https://www.acronos.com/DesignPatterns/template-method.html)</sup>

## References

1. [Template Method, Refactoring.Guru](https://refactoring.guru/design-patterns/template-method)
2. [Template Method, Design Patterns, Brian Davis](https://www.acronos.com/DesignPatterns/template-method.html)
3. [Chapter 5. Behavioral Patterns, Design Patterns: Elements of Reusable Object-Oriented Software, O'Reilly](https://www.oreilly.com/library/view/design-patterns-elements/0201633612/ch05.html)
4. [Inversion of Control, Martin Fowler](https://www.martinfowler.com/bliki/InversionOfControl.html)
5. [Template Method in Java, Refactoring.Guru](https://refactoring.guru/design-patterns/template-method/java/example)
6. [Form Template Method, Refactoring.Guru](https://refactoring.guru/form-template-method)
7. [Design Patterns: Elements of Reusable Object-Oriented Software, InformIT](https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-software-9780201633610)
8. [The GoF Design Patterns Memory, CiteSeerX](https://citeseerx.ist.psu.edu/document?doi=4619b65fe1aa3a868e56b14c796b29118df82f4d&repid=rep1&type=pdf)
9. [Strategy vs Template Method, Anti-Pattern Driven Design Pattern Tutorial](https://takt.dev/design-pattern/advanced/comparisons/strategy-template)
10. [Template Method vs Alternatives: When to Use Each, System Overflow](https://www.systemoverflow.com/learn/behavioral-patterns/template-method-pattern/template-method-vs-alternatives-when-to-use-each)
11. [Template Method, JavaScript Codex](https://javascriptcodex.com/template-method/)
12. [Class AbstractList, Java SE 24 API documentation, Oracle](https://docs.oracle.com/en/java/javase/24/docs/api/java.base/java/util/AbstractList.html)
13. [Call Super, Martin Fowler](https://martinfowler.com/bliki/CallSuper.html)
14. [Using the JDBC Core Classes, Spring Framework reference](https://docs.spring.io/spring-framework/reference/data-access/jdbc/core.html)
15. [Template Method Design Pattern, Design Patterns In Action](https://www.designpatternsinaction.com/pattern/template-method)
16. [Defect frequency and design patterns: an empirical study of industrial code, M. Vokác, IEEE Transactions on Software Engineering](https://www.researchgate.net/publication/3188469_Defect_frequency_and_design_patterns_an_empirical_study_of_industrial_code)
17. [An empirical study on the influence of pattern roles on change-proneness, Empirical Software Engineering](https://link.springer.com/article/10.1007/s10664-010-9148-2)

---
*Initially written Sep 17, 2026 · Reviewed: Oct 15, 2026 · Edited: Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 软件与编程 › Software engineering and development process › Software design and architecture › Titles Mu to Z

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/template-method-pattern

English original: https://www.edgepedia.org/template-method-pattern
