- Python Design Patterns - Home
- Python Design Patterns - Introduction
- Python Design Patterns - Gist
- Model View Controller Pattern
- Python Design Patterns - Singleton
- Python Design Patterns - Factory
- Python Design Patterns - Builder
- Python Design Patterns - Prototype
- Python Design Patterns - Facade
- Python Design Patterns - Command
- Python Design Patterns - Adapter
- Python Design Patterns - Decorator
- Python Design Patterns - Proxy
- Chain of Responsibility Pattern
- Python Design Patterns - Observer
- Python Design Patterns - State
- Python Design Patterns - Strategy
- Python Design Patterns - Template
- Python Design Patterns - Flyweight
- Python Design Patterns - Abstract Factory
- Python Design Patterns - Object Oriented
- Object Oriented Concepts Implementation
- Python Design Patterns - Iterator
- Python Design Patterns - Dictionaries
- Python Design Patterns - Lists Data Structure
- Python Design Patterns - Sets
- Python Design Patterns - Queues
- Python Design Patterns - Strings & Serialization
- Python Design Patterns - Concurrency
- Python Design Patterns - Anti Pattern
- Python Design Patterns - Exception Handling
Python Design Patterns Resources
Python Design Patterns - Template Pattern
A template pattern defines a basic algorithm in a base class using abstract operation where subclasses override the concrete behavior. The template pattern keeps the outline of algorithm in a separate method. This method is referred as the template method.
Following are the different features of the template pattern −
It defines the skeleton of algorithm in an operation
It includes subclasses, which redefine certain steps of an algorithm.
Example - Usage of Template Pattern
main.py
class MakeMeal:
def prepare(self): pass
def cook(self): pass
def eat(self): pass
def go(self):
self.prepare()
self.cook()
self.eat()
class MakePizza(MakeMeal):
def prepare(self):
print("Prepare Pizza")
def cook(self):
print("Cook Pizza")
def eat(self):
print("Eat Pizza")
class MakeTea(MakeMeal):
def prepare(self):
print("Prepare Tea")
def cook(self):
print("Cook Tea")
def eat(self):
print("Eat Tea")
makePizza = MakePizza()
makePizza.go()
print(25*"+")
makeTea = MakeTea()
makeTea.go()
Output
The above program generates the following output −
Prepare Pizza Cook Pizza Eat Pizza +++++++++++++++++++++++++ Prepare Tea Cook Tea Eat Tea
Explanation
This code creates a template to prepare meal. Here, each parameter represents the attribute to create a part of meal like tea, pizza, etc.
The output represents the visualization of attributes.
Advertisements