Template Method Pattern: Definition, Example, and Use Cases
Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps without changing the overall algorithm structure.How It Works
The Template Method Pattern works like a recipe where the main steps are fixed, but some details can change. Imagine baking a cake: the recipe tells you the order of steps, but you can choose different flavors or decorations. Similarly, this pattern defines a method with a fixed sequence of operations, but lets subclasses customize some steps.
This approach helps keep the overall process consistent while allowing flexibility in parts that vary. The base class has the 'template method' that calls other methods, some of which are implemented in the base class and others left abstract for subclasses to fill in.
Example
This example shows a base class with a template method and two subclasses that customize parts of the process.
from abc import ABC, abstractmethod class DataProcessor(ABC): def process(self): self.load_data() self.transform_data() self.save_data() def load_data(self): print("Loading data") @abstractmethod def transform_data(self): pass def save_data(self): print("Saving data") class CSVProcessor(DataProcessor): def transform_data(self): print("Transforming CSV data") class JSONProcessor(DataProcessor): def transform_data(self): print("Transforming JSON data") # Using the template method csv = CSVProcessor() csv.process() json = JSONProcessor() json.process()
When to Use
Use the Template Method Pattern when you have an algorithm with fixed steps but want to allow subclasses to change some parts. It is helpful when you want to avoid code duplication and keep the overall process consistent.
Real-world examples include frameworks where the main workflow is defined, but users can customize specific steps, like data processing pipelines, game development (game loop steps), or UI rendering sequences.
Key Points
- The pattern defines a fixed algorithm structure in a base class method.
- Subclasses override specific steps without changing the algorithm's order.
- Helps reuse code and enforce consistent workflows.
- Common in frameworks and libraries to allow customization.