Template Method
The template method pattern defines the skeleton of an algorithm in a superclass, but lets subclasses override specific steps without changing the structure of the algorithm itself.
TL;DR
Ensures that an algorithm is implemented using the correct steps (possibly with pre- and post- transformation notifications, for example) while letting the algorithm itself be implemented by a subclass.
Problem
Suppose your application processes data from various inputs, such as JSON, CSV, and SQL. In all cases the application reads the data, transforms it, and then saves it. You need to ensure that the same process takes place, so a naive solution is to create multiple classes and try to enforce the same process on all.
Solution
The solution is fairly straightforward, using a common interface that does not implement the transformation steps, but implements everything in else.
from abc import ABC, abstractmethod
class DataProcessor(ABC):
def process(self):
self.read_data()
self.transform_data()
self.save_data()
def read_data(self):
print("Reading data...")
@abstractmethod
def transform_data(self):
pass
def save_data(self):
print("Saving data...")
class CSVDataProcessor(DataProcessor):
def transform_data(self):
print("Transforming CSV data")
class JSONDataProcessor(DataProcessor):
def transform_data(self):
print("Transforming JSON data")
# Usage
processor = CSVDataProcessor()
processor.process()