Template Method Pattern in Python
Template Method preserves workflow order while subclasses override the parts that vary.
What is Template Method Pattern?
Template Method preserves workflow order while subclasses override the parts that vary.
Define an algorithm skeleton while allowing subclasses to customize selected steps.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
from abc import ABC, abstractmethod
class DataPipeline(ABC):
# Template Method: fix the workflow and customize selected steps.
def run(self):
# Keep the algorithm order stable.
return ["read", self.process(), "save"]
@abstractmethod
def process(self): pass
class CsvPipeline(DataPipeline):
def process(self): return "process CSV"
print(" -> ".join(CsvPipeline().run()))
Expected output
read -> process CSV -> save
How it works
DataPipeline.run fixes the sequence while CsvPipeline supplies the processing step.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.