Open In App

Template Method – Python Design Patterns

Last Updated : 21 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The Template method is a Behavioral Design Pattern that defines the skeleton of the operation and leaves the details to be implemented by the child class. Its subclasses can override the method implementations as per need but the invocation is to be in the same way as defined by an abstract class. It is one of the easiest among the Behavioral design pattern to understand and implements. Such methods are highly used in framework development as they allow us to reuse the single piece of code at different places by making certain changes. This leads to avoiding code duplication also.
 

Problem without using Template Method

Imagine you are working on a Chatbot application as a software developer which uses data mining techniques to analyze the data of the corporate documents. Initially, your applications were fine with the pdf version of the data only but later your applications also require to collect and convert data from other formats also such as XML, CSV, and others. After implementing the whole scenario for the other formats also, you noticed that all the classes have lots of similar code. Part of the code like analyzing and processing was identical in almost all classes whereas they differ in dealing with the data.
 

Problem-Template-Method

Problem-Template-Method

 

Solution using Template Method

Let’s discuss the solution to the above-described problem using the template method. It suggests to break down the code into a series of steps and convert these steps into methods and put series call inside the template_function. Hence we created the template_function separately and create methods such as get_xml, get_pdf and get_csv for dealing with the code separately.
 

Python3




""" method to get the text of file"""
def get_text():
     
    return "plain_text"
 
""" method to get the xml version of file"""
def get_xml():
     
    return "xml"
 
""" method to get the pdf version of file"""
def get_pdf():
     
    return "pdf"
 
"""method to get the csv version of file"""
def get_csv():
     
    return "csv"
 
"""method used to convert the data into text format"""
def convert_to_text(data):
     
    print("[CONVERT]")
    return "{} as text".format(data)
 
"""method used to save the data"""
def saver():
     
    print("[SAVE]")
 
"""helper function named as template_function"""
def template_function(getter, converter = False, to_save = False):
 
    """input data from getter"""
    data = getter()
    print("Got `{}`".format(data))
 
    if len(data) <= 3 and converter:
        data = converter(data)
    else:
        print("Skip conversion")
     
    """saves the data only if user want to save it"""
    if to_save:
        saver()
 
    print("`{}` was processed".format(data))
 
 
"""main method"""
if __name__ == "__main__":
 
    template_function(get_text, to_save = True)
 
    template_function(get_pdf, converter = convert_to_text)
 
    template_function(get_csv, to_save = True)
 
    template_function(get_xml, to_save = True)


Output

Got `plain_text`
Skip conversion
[SAVE]
`plain_text` was processed
Got `pdf`
[CONVERT]
`pdf as text` was processed
Got `csv`
Skip conversion
[SAVE]
`csv` was processed

Class Diagram

Following is the class diagram for the Template Method
 

Class-diagram-template-method

Class-diagram-template-method

 

Advantages

 

  • Equivalent Content: It’s easy to consider the duplicate code in the superclass by pulling it there where you want to use it.
  • Flexibility: It provides vast flexibility such that subclasses are able to decide how to implement the steps of the algorithms.
  • Possibility of Inheritance: We can reuse our code as the Template Method uses inheritance which provides the ability of code reusability.

 

Disadvantages

 

  • Complex Code: The code may become enough complex sometimes while using the template method such that it becomes too much hard to understand the code even by the developers who are writing it.
  • Limitness: Clients may ask for the extended version because sometimes they feel lack of algorithms in the provided skeleton.
  • Violation: It might be possible that by using Template method, you may end up with violating the Liskov Substitution Principle which is definitely not the good thing to follow.

 

Applicability

 

  • Extension by Clients: This method is always preferred to use when you want to let clients extend the algorithm using particular steps but with not the whole structure of the algorithm.
  • Similar Algorithms: When you have a lot of similar algorithms with minor changes, its always better to use the template design pattern because if some changes occur in the algorithm, then you don’t have to make changes in each algorithm.
  • Development of Frameworks: It is highly recommended to use the template design pattern while developing a framework because it will help us to avoid the duplicate code as well as reusing the piece of code again and again by making certain changes.

Further Read – Template Method in Java
 



Previous Article
Next Article

Similar Reads

Iterator Method - Python Design Patterns
Iterator method is a Behavioral Design Pattern that allows us to traverse the elements of the collections without taking the exposure of in-depth details of the elements. It provides a way to access the elements of complex data structure sequentially without repeating them.According to GangOfFour, Iterator Pattern is used " to access the elements o
4 min read
Factory Method - Python Design Patterns
Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the client, and for creating the new type of object, the
5 min read
Abstract Factory Method - Python Design Patterns
Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group of individual factories. Basically, here we try t
4 min read
Singleton Method - Python Design Patterns
Prerequisite: Singleton Design pattern | Introduction What is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class to create methods and specify the objects. Singlet
5 min read
Prototype Method - Python Design Patterns
Prototype Method is a Creational Design Pattern which aims to reduce the number of classes used for an application. It allows you to copy existing objects independent of the concrete implementation of their classes. Generally, here the object is created by copying a prototypical instance during run-time. It is highly recommended to use Prototype Me
5 min read
Builder Method - Python Design Patterns
Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code, we can produce different types and representatio
5 min read
Adapter Method - Python Design Patterns
Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to create a bridge between two incompatible interfaces.
4 min read
Bridge Method - Python Design Patterns
The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to organize the class hierarchy. Elements of Bridge Des
5 min read
Composite Method - Python Design Patterns
Composite Method is a Structural Design Pattern which describes a group of objects that is treated the same way as a single instance of the same type of the objects. The purpose of the Composite Method is to Compose objects into Tree type structures to represent the whole-partial hierarchies. One of the main advantages of using the Composite Method
5 min read
Decorator Method - Python Design Patterns
Decorator Method is a Structural Design Pattern which allows you to dynamically attach new behaviors to objects without changing their implementation by placing these objects inside the wrapper objects that contains the behaviors. It is much easier to implement Decorator Method in Python because of its built-in feature. It is not equivalent to the
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg