Design Patterns — Fast Recall (Python)
Template Method — fixed skeleton, variable steps
- What: a base class defines the algorithm's outline; subclasses fill in specific steps (hooks).
- Why / when: several flows share the same sequence but differ in a step or two — data pipelines (load→process→save), report generators.
- Benefit: the invariant order lives in one place; you can't accidentally reorder steps.
- vs Strategy: Template uses inheritance (override steps); Strategy uses composition (swap the whole algorithm).
1class Report:
2 def generate(self): # the fixed skeleton
3 self.load(); self.render(); print("done")
4 def load(self): raise NotImplementedError
5 def render(self): raise NotImplementedError
6
7class CSVReport(Report):
8 def load(self): print("read csv")
9 def render(self): print("render table")
10
11CSVReport().generate() # read csv / render table / done