Template Method Pattern
Part of the Object Oriented Programming section of Coddy's Python journey. Lesson 52 of 64.
The Template Method Pattern defines the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm's structure.
Here is a base class with a template method:
class DataProcessor:
def process(self):
"""Template method defining the algorithm structure"""
self.read_data()
self.process_data()
self.save_data()
def read_data(self):
print("Reading data...")
def process_data(self):
raise NotImplementedError("Subclasses must implement this")
def save_data(self):
print("Saving data...")The template method process() defines the algorithm steps, while process_data() is left for subclasses to implement.
Create concrete classes that implement the abstract method:
class CSVProcessor(DataProcessor):
def process_data(self):
print("Processing CSV data")
class JSONProcessor(DataProcessor):
def process_data(self):
print("Processing JSON data")Each concrete class provides its own implementation of the required step.
Use the template method:
csv_processor = CSVProcessor()
csv_processor.process()
print() # Empty line
json_processor = JSONProcessor()
json_processor.process()Create another example with a game template:
class Game:
def play(self):
"""Template method for playing a game"""
self.start_game()
self.play_game()
self.end_game()
def start_game(self):
print("Game started!")
def play_game(self):
raise NotImplementedError("Define the game rules")
def end_game(self):
print("Game ended!")
class Chess(Game):
def play_game(self):
print("Playing chess - thinking strategically...")
class Soccer(Game):
def play_game(self):
print("Playing soccer - running and kicking...")
chess = Chess()
chess.play()Output:
Reading data...
Processing CSV data
Saving data...
Reading data...
Processing JSON data
Saving data...
Game started!
Playing chess - thinking strategically...
Game ended!Key Point: The Template Method Pattern defines a common algorithm structure in the parent class while letting subclasses customize specific steps. The parent class controls the overall flow, but subclasses provide the specific implementations. This ensures consistent structure while allowing flexibility in individual steps.
Challenge
MediumImplement the Template Method pattern in template.py. The abstract Report class owns the template method generate(), which always runs the same three steps in the same order: header(), body(), footer().
header()is shared by every report and prints=== Report ===.body()is abstract: each subclass prints its own content.footer()is a hook with a default,=== End ===, that a subclass may override.
Then write the two concrete reports:
SalesReport(total)stores the total inself._totaland printsTotal sales: {total}in its body.InventoryReport(items)stores the list inself._items, printsItem: {item}for every item in its body, and overrides the footer to print=== {count} items ===.
driver.py is locked: it builds reports and calls generate() on them. Only the steps differ between the subclasses; the order of the steps lives in the base class once.
Try it yourself
from template import SalesReport, InventoryReport
# Test case handler (do not change)
test_case = input()
if test_case == "sales_test":
SalesReport(1500).generate()
elif test_case == "inventory_test":
InventoryReport(["Laptop", "Mouse"]).generate()
elif test_case == "both_test":
for report in [SalesReport(200), InventoryReport(["Pen"])]:
report.generate()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers11Design Patterns Part 2
Command PatternAdapter PatternDecorator PatternTemplate Method PatternState PatternComposite Pattern3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User ClassesBorrowing SystemSearch FunctionalityAdmin InterfaceTesting and IntegrationPractice on your own: Online Python compiler