Learn the design pattern "Template Method" in Python

As a material for learning GoF design patterns, the book "Introduction to Design Patterns Learned in the Augmented and Revised Java Language" seems to be helpful. However, since the examples taken up are based on JAVA, I tried the same practice in Python to deepen my understanding.

■ Template Method

The Template Method pattern is one of the design patterns defined by GoF (Gang of Four; 4 gangs). It belongs to "behavioral patterns". The purpose of the Template Method pattern is to predetermine a rough algorithm for a process and leave the specific design of that algorithm to a subclass. Therefore, it is often used as a means for building a system framework.

UML class diagram templatemethod.png (The above is quoted from Wikipedia)

■ Sample program of "Template Method"

Actually, I would like to run a sample program that utilizes the Template Method pattern and check the following behavior.

--Display the letter "H" five times in a row. In addition, before and after, it is displayed surrounded by "<<" and ">>". --Display the character string "Hello, World!" 5 times in a row. In addition, it is displayed surrounded by a frame.

$ python Main.py 
<<HHHHH>>

+-------------+
|Hello, World!|
|Hello, World!|
|Hello, World!|
|Hello, World!|
|Hello, World!|
+-------------+

■ Details of sample program

Similar code has been uploaded to the Git repository. https://github.com/ttsubo/study_of_design_pattern/tree/master/TemplateMethod

--Directory structure

.
├── Main.py
└── templatemethod
    ├── __init__.py
    └── display.py

(1) The role of AbstractClass

The ʻAbstractClassrole implements the template method. Also, declare the abstract method used in the template method. This abstract method is implemented by the subclassConcreteClass role. In the sample program, the ʻAbstractDisplay class serves this role.

templatemethod/display.py


from abc import ABCMeta, abstractmethod

class AbstractDisplay(metaclass=ABCMeta):
    @abstractmethod
    def print(self):
        pass

    @abstractmethod
    def open(self):
        pass

    @abstractmethod
    def close(self):
        pass

    def display(self):
        self.open()
        for _ in range(5):
            self.print()
        self.close()

(2) The role of ConcreteClass

ʻConcretely implement the abstract class defined by the role of AbstractClass. The method implemented here is called from the template method that plays the role of ʻAbstractClass. In the sample program, the CharDisplay and StringDisplay classes serve this role.

templatemethod/display.py


class CharDisplay(AbstractDisplay):
    def __init__(self, ch):
        self.__ch = ch

    def open(self):
        print('<<', end='')

    def print(self):
        print(self.__ch, end='')

    def close(self):
        print('>>')

class StringDisplay(AbstractDisplay):
    def __init__(self, string):
        self.__string = string
        self.__width = len(string)

    def open(self):
        self.__printLine()

    def print(self):
        print("|{0}|".format(self.__string))

    def close(self):
        self.__printLine()

    def __printLine(self):
        print('+', end='')
        for _ in range(self.__width):
            print('-', end='')
        print('+')

(3) The role of Client (user)

In the sample program, the startMain method serves this role.

Main.py


from templatemethod.display import CharDisplay, StringDisplay

def startMain():
    d1 = CharDisplay('H')
    d2 = StringDisplay("Hello, World!")
    d1.display()
    print("")
    d2.display()

if __name__ == '__main__':
    startMain()

■ Reference URL

-[Finishing "Introduction to Design Patterns Learned in Java Language" (Not)](https://medium.com/since-i-want-to-start-blog-that-looks-like-men-do/java Introduction to Design Patterns Learned in Language-Finishing-Not-2cc9b34a30b2)

Recommended Posts

Learn the design pattern "Template Method" in Python
Learn the design pattern "Factory Method" in Python
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
Learn the design pattern "Flyweight" in Python
Learn the design pattern "Observer" in Python
Learn the design pattern "Memento" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Command" in Python
Learn the design pattern "Visitor" in Python
Learn the design pattern "Bridge" in Python
Learn the design pattern "Mediator" in Python
Learn the design pattern "Decorator" in Python
Learn the design pattern "Iterator" in Python
Learn the design pattern "Strategy" in Python
Learn the design pattern "Composite" in Python
Learn the design pattern "State" in Python
Learn the design pattern "Adapter" in Python
Python Design Pattern --Template method
Learn the design pattern "Abstract Factory" in Python
Learn the design pattern "Chain of Responsibility" in Python
Design Pattern #Template Method
Learn the design pattern "Singleton" with Python
Learn the design pattern "Facade" with Python
Template Method pattern in Java
Implement the Singleton pattern in Python
Singleton pattern in Python
Design Pattern #Factory Method
Visitor pattern in Python
[Details] Template Method pattern
I tried the least squares method in Python
To dynamically replace the next method in python
Simplex method (simplex method) in Python
Private method in python
Try implementing the Monte Carlo method in Python
[Gang of Four] Design pattern learning --Template Method
Determine the threshold using the P tile method in python
Implemented k-nearest neighbor method in python from scikit learn
I wrote a design pattern in kotlin Template edition
Download the file in Python
Find the difference in Python
Learn cumulative sum in Python
Design Patterns in Python: Introduction
Implement method chain in Python
Learn exploration in Python # 1 Full exploration
Suppressing method overrides in Python
How to use the __call__ method in a Python class
Getting the arXiv API in Python
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
Get the desktop path in Python
Try implementing extension method in python
Get the script path in Python
In the python command python points to python3.8
Implemented label propagation method in Python
Simulate Monte Carlo method in Python
Hit the web API in Python
Hash method (open address method) in Python
I wrote the queue in Python
Calculate the previous month in Python