📢 This article was translated by gemini-2.5-flash
Template Method Pattern: Class Behavioral Pattern
Intent
Defines an algorithm’s skeleton in an operation, letting subclasses override specific steps later. Template Method allows subclasses to redefine parts of an algorithm without messing with its structure.
Structure

Key components:
AbstractClass(抽象类): Defines abstract primitive operations that concrete subclasses will redefine to implement the algorithm’s steps. It also implements the template method, which sets up the algorithm’s skeleton. This template method calls both primitive operations and other operations defined inAbstractClassor other objects.ConcreteClass(具体类): Implements the primitive operations to complete the algorithm’s steps specific to that subclass.
When to Use It
Use the Template Method pattern when:
- You want to implement an algorithm’s unchanging parts just once, letting subclasses handle the variable behaviors.
- You have common behavior across multiple subclasses that should be pulled into a single parent class to prevent code duplication.
- You need to control how subclasses extend functionality. The template method calls ‘hook’ operations (default behaviors subclasses can override) at specific points, limiting extensions to these predefined spots.
Example
Imagine a classroom: students attend and do homework; teachers lecture and grade.
| |