Template Method
Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
classDiagram
class AbstractClass {
+templateMethod()
+baseOperation1()
+baseOperation2()
+baseOperation3()
+requiredOperations1()
+requiredOperation2()
+hook1()
+hook2()
}
class ConcreteClass1 {
+requiredOperations1()
+requiredOperation2()
}
class ConcreteClass2 {
+requiredOperations1()
+requiredOperation2()
+hook1()
}
AbstractClass <|-- ConcreteClass1
AbstractClass <|-- ConcreteClass2
When to use
Use the Template Method pattern when you want to let clients extend only particular steps of an algorithm, but not the whole algorithm or its structure. Use when you have several classes that contain almost identical algorithms with some minor differences.
Explanation
Problem
Imagine that you’re creating a data mining application. The app goes to various corporate documents (PDF, DOC, CSV), extracts meaningful data from them, and formats it into a uniform text file.
You created PDFMiner, DocMiner, CsvMiner. You noticed that a lot of code (opening file, analyzing raw data, closing file) is repeated. The only difference is how they extract data.
Solution
The Template Method pattern suggests that you break down an algorithm into a series of steps, turn these steps into methods, and put a series of calls to these methods inside a single “template method.”
The steps may either be abstract, or have some default implementation. Subclasses can override these steps.
Real world problem
- House Building: Build Foundation -> Build Walls -> Build Roof -> Add Windows. Concrete/Wooden houses differ in implementation of steps, but sequence is same.
- React Components:
componentDidMount,render,componentWillUnmountare hooks in the React component lifecycle (Template Method). - Unit Tests:
setup(),test(),teardown().
Pros and Cons
| Pros | Cons |
|---|---|
| - Code Reuse: You can let clients override only certain parts of a large algorithm, making them less affected by changes that happen to other parts of the algorithm. - Duplication: You can pull the duplicate code into a superclass. |
- Limitation: Some clients may be limited by the provided skeleton of an algorithm. - Liskov Substitution Principle: You might violate the Liskov Substitution Principle by suppressing a default step implementation via a subclass. |
Comparison
- Factory Method: Factory Method is a specialization of Template Method.
- Strategy: Template Method works at the class level (inheritance). Strategy works at the object level (composition).
- Template Method: Template Method defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps.
Code example
Typescript
Php