What is the 'Template Method' design pattern?
sobes.tech AI
Answer from AI
"Template Method" is a behavioral design pattern that defines the skeleton of an algorithm in a base class, allowing subclasses to override certain steps of the algorithm without changing its overall structure.
Key components:
- Abstract base class: Contains the template method and abstract or concrete methods representing the steps of the algorithm.
- Concrete subclasses: Inherit from the abstract base class and implement the abstract methods, providing specific logic for certain steps, or override concrete methods.
- Template method: A non-abstract method in the base class that defines the sequence of calls to other methods (abstract, concrete, or hook methods), forming the framework of the algorithm.
Working principle:
The base class defines the "skeleton" of the algorithm in the template method. Some steps of this algorithm can be implemented in the base class (concrete methods), while others remain abstract, requiring implementation in subclasses. Hook methods may also be provided—optional methods that subclasses can override to extend functionality at certain stages of the algorithm but are not mandatory steps.
Advantages:
- Allows code reuse of the base class.
- Provides flexibility by allowing subclasses to customize parts of the algorithm.
- Limits the ability to change the algorithm's structure, as the template method remains unchanged.
Disadvantages:
- Increases code complexity due to the need to create a class hierarchy.
- Some subclasses may be forced to implement methods they do not need.
Example:
Imagine the process of making a beverage. The base class BeverageTemplate defines steps: boil water, add ingredients, pour into a cup. Subclasses Tea and Coffee implement specific steps "boil" and "add ingredients".
# Abstract base class (can be a regular class,
# if all steps have a default implementation)
class BeverageTemplate:
def prepare_beverage(self):
# Template method - defines the structure of the algorithm
self.boil_water()
self.brew()
self.pour_in_cup()
self.add_condiments()
def boil_water(self):
# Concrete step with default implementation
print("Boiling water")
# Abstract steps - must be implemented in subclasses
def brew(self):
raise NotImplementedError("Subclass must implement abstract method")
def add_condiments(self):
raise NotImplementedError("Subclass must implement abstract method")
def pour_in_cup(self):
# Concrete step with default implementation
print("Pouring into cup")
# Concrete subclasses
class Coffee(BeverageTemplate):
def brew(self):
print("Dripping coffee through filter")
def add_condiments(self):
print("Adding sugar and milk")
class Tea(BeverageTemplate):
def brew(self):
print("Steeping the tea bag")
def add_condiments(self):
print("Adding lemon")
# Usage
print("Making coffee...")
coffee_maker = Coffee()
coffee_maker.prepare_beverage()
print("\nMaking tea...")
tea_maker = Tea()
tea_maker.prepare_beverage()