[Template method] Template method of design pattern

Introduction

The template method pattern is a relatively simple design pattern. The basic idea is to abstract the fixed process or logic into a method according to possible changes, and put the changed parts into derived classes to implement. It is to define the framework of the processing process in the parent class or abstract class, and implement specific processing in the subclass!
For example, there are multiple servers providing services. The types of services are different, but they are all necessary for business. We need to implement a client to connect to the server. During the connection process of each server, the protocol used is Consistent, the operation process is also the same:

  • Preparation
  • Connect to server
  • Handle business
  • Disconnect
  • cleanup

However, the preparation work required to connect to different servers may be different for each item of work. In this case, the above process can be abstracted into a method connect(), and the individual items of work are encapsulated into ready_work() , connect_to_server(), process_work(), disconnect_to_server(), clear_work() and several other methods. And implement them separately in the client subclass.
The connect method at this time is called the template method; this mode is the template method mode.

Code

This example is a class that displays the output content in different ways.
The template method is display.
The specific processing is encapsulated as three methods: open, print, close. Two
display methods:

  1. Character display, enclosed by <<>>
  2. String display, the first and last lines are filled with ±—+, the first and last lines of the content are filled with |

kind

Class Name Desc
AbstractDisplay Abstract class that implements the display method
CharDisplay Subclasses that implement specific processing
StringDisplay Subclasses that implement specific processing
TemplateMethodClient Test client class

UML class diagram

Class Diagram

AbstractDisplay

"""
@Time: 2023/3/26 20:43
@Auth: CivilDog
@File: AbstractDisplay.py
@IDE: PyCharm
@Motto: Nothing is impossible
"""
import abc


class AbstractDisplay(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def open(self):
        pass

    @abc.abstractmethod
    def print(self):
        pass

    @abc.abstractmethod
    def close(self):
        pass

    def display(self):
        self.open()
        for i in range(0, 5):
            self.print()
        self.close()

CharDisplay

"""
@Time: 2023/3/26 20:46
@Auth: CivilDog
@File: CharDisplay.py
@IDE: PyCharm
@Motto: Nothing is impossible
"""
from DesignMode.TemplateMethodMode.AbstractDisplay import AbstractDisplay


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(">>")

StringDisplay

"""
@Time: 2023/3/26 20:50
@Auth: CivilDog
@File: StringDisplay.py
@IDE: PyCharm
@Motto: Nothing is impossible
"""
from DesignMode.TemplateMethodMode.AbstractDisplay import AbstractDisplay


class StringDisplay(AbstractDisplay):

    def __init__(self, string):
        self.__string = string

    def open(self):
        self.print_line()

    def print(self):
        print("|" + self.__string + "|")

    def close(self):
        self.print_line()

    def print_line(self):
        print("+", end="")
        for i in range(len(self.__string)):
            print("-", end="")
        print("+")

TemplateMethodClient

"""
@Time: 2023/3/26 20:54
@Auth: CivilDog
@File: TemplateMethodClient.py
@IDE: PyCharm
@Motto: Nothing is impossible
"""
from DesignMode.TemplateMethodMode.CharDisplay import CharDisplay
from DesignMode.TemplateMethodMode.StringDisplay import StringDisplay


class TemplateMethodClient(object):
    @staticmethod
    def run(*args, **kwargs):
        char_display = CharDisplay("H")
        str_display = StringDisplay("Hello World!")
        char_display.display()
        str_display.display()


if __name__ == '__main__':
    TemplateMethodClient.run()

output

<<HHHHH>>
+------------+
|Hello World!|
|Hello World!|
|Hello World!|
|Hello World!|
|Hello World!|
+------------+

Process finished with exit code 0

Summarize

There are only two roles in the template method pattern: abstract class and concrete class. The unified process is put into the abstract class and becomes an independent method. This mode can make the logic processing universal. If you want to display the output content in other styles, you only need to inherit AbstractDisplay, implement the open print close method and then call the display display.
And once the process changes, you only need to modify the template method. However, when new steps occur in the process, they need to be added in each subclass.

"Illustrative Design Pattern"

Guess you like

Origin blog.csdn.net/weixin_43500200/article/details/129784629