This is a continuation of the design pattern series.
I had blogged about Singleton once, when I was using it very frequently. This blog post is about the use of the Template Design Pattern. So let’s discuss the pattern and then we can dive into the code and its implementation and see a couple of use cases.
The Template Method Design Pattern is a actually a pattern to follow when there are a series of steps, which need to be followed in a particular order. Well, the next question that arises is, “Isn’t every program a series of steps that has to be followed in a particular order?”
The answer is Yes!
This pattern diverges when it becomes a series of functions that has to be executed in the given order. As the name suggests it is a Template Method Design pattern, with stress on the word method, because that is what makes it a different ball game all together.
Let’s understand this with an example of
Eating in a Buffet. Most of us have follow a set of similar specific steps, when eating at a
Buffet. We all go for the starters first, followed by main course and then finally, dessert. (Unless it is Barbeque Nation then it’s starters, starters and starters :))
So this is kind of a template for everyone
Starters --> Main course --> Desserts.
Keep in mind that content in each category can be different depending on the person but the order doesn’t change which gives a way to have a template in the code. The primary use of any
design pattern is to reduce duplicate code or solve a specific problem. Here this concept solves the problem of code duplication.
The concept of
Template Method Design Pattern depends on, or rather is very tightly coupled with
Abstract Classes themselves are a template for
derived classes to follow but
Template Design Pattern takes it one notch higher, where you have a template in a template. Here’s an example of a
from abc import ABC, abstractmethod class BuffetHogger(ABC): @abstractmethod def starter_hogging(self): pass @abstractmethod def main_course_hogging(self): pass @abstractmethod def dessert_hogging(self): pass def template_hogging(self): self.starter_hogging() self.main_course_hogging() self.dessert_hogging()
So if you see here the
dessert_hogging are abstract class that means base class has to implement it while
template_hogging uses these methods and will be same for all base class.
Let’s have a
Farhaan class who is a
BuffetHogger and see how it goes.
class Farhaan(BuffetHogger): def starter_hogging(self): print("Eat Chicken Tikka") print("Eat Kalmi Kebab") def __call__(self): self.template_hogging() def main_course_hogging(self): print("Eat Biryani") def dessert_hogging(self): print("Eat Phirni")
BuffetHoggerclasses as you want, and they’ll all have the same way of hogging. That’s how we solve the problem of code duplication