Course contentsShow
← Computer Science
Lesson 2293 of 2,87251. Design PatternsFree lesson

Template Method Pattern

Defining the skeleton of an algorithm in a base class, deferring specific steps to subclasses.

Template Method Pattern

You'll learn how to define a flexible algorithm skeleton in a parent class while letting subclasses customize specific steps without changing the overall structure.

The Core Idea

The Template Method Pattern defines the high-level structure of an algorithm in a base class, leaving certain steps abstract or overridable. Subclasses can then customize those specific steps without altering the algorithm's overall flow.

Think of it like a recipe framework: "First prepare ingredients, then cook, then serve" is fixed, but how you prepare (chop vs blend) or what you cook (pasta vs stir-fry) can vary by subclass.

How It Works

You create an abstract base class with:

  • A template method (usually final or non-overridable) that defines the algorithm's sequence
  • Abstract or "hook" methods that subclasses implement for customization

The template method calls these customizable steps in a predefined order, ensuring consistency while allowing flexibility.

class DataProcessor:
    def process(self):  # Template method
        self.load_data()
        self.transform_data()
        self.save_data()
    
    def load_data(self):
        raise NotImplementedError
    
    def transform_data(self):
        raise NotImplementedError
    
    def save_data(self):
        raise NotImplementedError

class CSVProcessor(DataProcessor):
    def load_data(self):
        print("Loading CSV...")
    
    def transform_data(self):
        print("Transforming CSV data...")
    
    def save_data(self):
        print("Saving to database...")

The process() method enforces the three-step workflow, but each subclass provides its own implementation details.

When to Use It

  • You have algorithms with common structure but varying details
  • You want to prevent subclasses from changing the algorithm's sequence
  • You need to enforce certain steps while allowing customization of others

Key Takeaway: The Template Method Pattern creates a skeleton algorithm with fixed structure but flexible steps, promoting code reuse while preventing subclasses from breaking the intended workflow.