Menu
Coddy logo textTech

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 icon

Challenge

Medium

Implement 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 in self._total and prints Total sales: {total} in its body.
  • InventoryReport(items) stores the list in self._items, prints Item: {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()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Python compiler