Template Method Pattern

The Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class, allowing subclasses to override specific steps without changing the overall structure. It promotes code reuse and enforces a consistent process flow.

Key Principles

Structure

Python Example: Data Processing Pipeline

from abc import ABC, abstractmethod

# Abstract Class with Template Method
class DataProcessor(ABC):
    # Template method – defines algorithm skeleton
    def process(self):
        self.load_data()
        self.validate_data()
        self.transform_data()  # Optional hook
        self.save_data()
        print("Processing complete!\n")

    @abstractmethod
    def load_data(self):
        pass

    @abstractmethod
    def validate_data(self):
        pass

    @abstractmethod
    def save_data(self):
        pass

    # Optional hook (default implementation)
    def transform_data(self):
        print("Default transformation (no-op)")

# Concrete Classes
class CSVProcessor(DataProcessor):
    def load_data(self):
        print("Loading data from CSV file")

    def validate_data(self):
        print("Validating CSV structure")

    def save_data(self):
        print("Saving processed data to database")

    def transform_data(self):  # Override hook
        print("Converting CSV to normalized format")

class JSONProcessor(DataProcessor):
    def load_data(self):
        print("Loading data from JSON API")

    def validate_data(self):
        print("Validating JSON schema")

    def save_data(self):
        print("Saving processed data to NoSQL store")

# Usage (Client Code)
if __name__ == "__main__":
    print("Processing CSV:")
    CSVProcessor().process()

    print("Processing JSON:")
    JSONProcessor().process()

Output:

Processing CSV:
Loading data from CSV file
Validating CSV structure
Converting CSV to normalized format
Saving processed data to database
Processing complete!

Processing JSON:
Loading data from JSON API
Validating JSON schema
Default transformation (no-op)
Saving processed data to NoSQL store
Processing complete!

When to Use Template Method

Summary: Template Method defines the algorithm skeleton in a base class and lets subclasses customize specific steps via overrides, ensuring consistent execution while allowing flexibility.