Baking a Code Recipe with Flexibility
In essence, the Template Method Design Pattern lets you bake a flexible code recipe, providing a solid foundation while allowing for creative variations and customizations to suit your specific needs.
from abc import ABC, abstractmethod
class AlgorithmTemplate(ABC):
def execute(self):
self.step1()
self.step2()
self.step3()
@abstractmethod
def step1(self):
pass
@abstractmethod
def step2(self):
pass
@abstractmethod
def step3(self):
pass
class ConcreteImplementation1(AlgorithmTemplate):
def step1(self):
print("ConcreteImplementation1: Step 1")
def step2(self):
print("ConcreteImplementation1: Step 2")
def step3(self):
print("ConcreteImplementation1: Step 3")
class ConcreteImplementation2(AlgorithmTemplate):
def step1(self):
print("ConcreteImplementation2: Step 1 (with variation)")
def step2(self):
print("ConcreteImplementation2: Step 2")
def step3(self):
print("ConcreteImplementation2: Step 3 (skipped)")
# Client code using the algorithm template
implementation1 = ConcreteImplementation1()
implementation1.execute()
print("\n") # Add a separator for visual clarity
implementation2 = ConcreteImplementation2()
implementation2.execute()