All Courses

Design Patterns Template in Python

Shashank Shanu

2 years ago

Design Patterns Template in Python | insideAIML
Table of Contents
  • Introduction
  • Template pattern
  • Explanation
    

Introduction

          Template pattern defines a basic algorithm in a base class using the abstract operation where subclasses override the concrete behavior.
Template patterns help to keep the algorithm outline in a separate method so this method is known as the template method.
Some of the different features of the template pattern-
  • Define is the skeleton of an algorithm in an operation.
  • Includes subclasses, which help us to the redefine certain steps of an algorithm.
Let’s take an example:
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 output of the above program-
Output | Insideaiml

Explanation

          The code creates a template to prepare food. Each parameter represents the attribute to create a part of food like coffee, Maggi, etc.
The output represents the visualization of attributes.
I hope you enjoyed reading this article and finally, you came to know about Design Patterns Template in Python.
   
For more such blogs/courses on data science, machine learning, artificial intelligence and emerging new technologies do visit us at InsideAIML.
Thanks for reading…
Happy Learning…

Submit Review