Design Pattern #Template Method

I practiced design patterns so that I could write code that was conscious of design. Other Design Patterns will be released frequently.

Preface

The primary goal is to understand when, what, and how to use design patterns. (I'm new to Java or a statically typed language, and I don't have a long history of python, so I think there are some things that aren't like Pythonista. If you have any suggestions, please teach me.)

This time, the Template Method of the pattern related to behavior.

What is Template Method?

A design pattern in which the superclass defines the processing framework and the subclass defines the specific content. Is it? In other words, since the algorithm is described by the template method of the superclass, it is not necessary to describe the algorithm one by one on the subclass side. Then, if programming is performed using the Template Method pattern, even if an error is found in the template method, it is possible to reduce the trouble of subsequent correction that only the template method needs to be corrected.

In other words, the rough algorithm should be decided in advance by the superclass, and the concrete design and processing of the algorithm should be done by the subclass.

Overview

The sample program created here displays "characters and character strings repeated 5 times". Here, it consists of three classes, AbstractDisplay, CharDisplay, and StringDisplay, and Main (executable file). The Display method is defined in the AbstractDisplay class. And in the display method, three methods, opening, printing and closing, are used. These three methods are also declared in the AbstractDisplay class, but they are intangible abstract methods. Here, the display method, which uses an abstract method, is the template method. The actual implementations of the open, print, and close methods are the CharDisplay and StringDisplay classes, which are subclasses of the AbstractDisplay class. There is a figure below.

abstract_display.py


from abc import ABCMeta, abstractmethod

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

    @abstractmethod     
    def printing(self):
        pass
        
    @abstractmethod 
    def closing(self):
        pass
    
    def display(self):
        self.opening()
        for i in range(5):
            self.printing()
        self.closing()

char_display.py


import sys
from abstract_display import AbstractDisplay

class CharDisplay(AbstractDisply):
    def __init__(self, ch):
        self.__ch  = ch
    
    def opening(self):
        sys.stdout.write('<<') #If you use print, a blank character will appear immediately after output.
    def printing(self):
        sys.stdout.write(self.__ch)
    
    def closing(self):
        print('>>')   

char_display.py


import sys
from abstract_display import AbstractDisplay

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

    def printing(self):
        self.print('|' + self.__string + '|')
     
    def closing(self):
        self.__print_line() 

    def __print_line(self):
        sys.stdout.write(''.join(('+', '-' * self.__width, '+\n')))  #If you use print, a blank character will appear immediately after output.

main.py


from char_display import CharDisplay
from string_display import StringDisplay


def main():
    d1 = CharDisplay('H')
    d2 = StringDisplay('Hello, World')
    d3 = StringDisplay('Hello')
    
    d1.display()
    d2.display()
    d3.display()

if __name__ == '__main__':
    main()

python main.py

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

What is the significance of abstract classes?

The actual processing content can only be understood by subclasses, but it seems important to shape the processing flow at the abstract class stage. If you have an abstract class, the subclass implements the methods that are in the abstract class. Then make the subclass responsible for implementing the method.

Summary

Abstract classes cannot be instantiated. I wondered what the class exists for, such as a class that cannot create an instance, but since the body of the method is not written in the abstract method, I do not know the specific processing content. However, it is possible to decide the name of the method and describe the process by the template method using that method, and by standardizing the process, the possibility of correction and bug can be reduced.

The design pattern is Separation of Concerns (http://en.wikipedia.org/wiki/%E9%96%A2%E5%BF%83%E3%81%AE%E5%88%86%E9%9B% I feel that A2) is the basis.

reference

Recommended Posts

Design Pattern #Template Method
Python Design Pattern --Template method
Design Pattern #Factory Method
[Details] Template Method pattern
Learn the design pattern "Template Method" in Python
Template Method pattern in Java
[Gang of Four] Design pattern learning --Template Method
Design Pattern #Builder
Design Pattern #Adapter
Design Pattern #Decorator
Design Pattern #Observer
Design Pattern #Strategy
Design Pattern #Singleton
Design Pattern #Proxy
[Gang of Four] Design pattern learning --Factory Method
Learn the design pattern "Factory Method" in Python
I wrote a design pattern in kotlin Template edition
Ore Ore Design Pattern: Glocal Variable
[Gang of Four] Design pattern learning
Introduction of data-driven controller design method
Design patterns to enjoy with frequently used Java libraries --Template Method patterns
GoF java design pattern rough summary
template
Learn the design pattern "Prototype" in Python
Learn the design pattern "Builder" in Python
[Gang of Four] Design pattern learning --Singleton
[Gang of Four] Design Pattern Learning --Decorator
[Gang of Four] Design pattern learning --Visitor
[Gang of Four] Design pattern learning --Mediator
Learn the design pattern "Observer" in Python
Learn the design pattern "Proxy" in Python
Learn the design pattern "Command" in Python
[Gang of Four] Design pattern learning --Iterator
GoF design pattern from the problem 2. Structure
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
[Gang of Four] Design pattern learning --Facade
[Gang of Four] Design pattern learning --Composite
[Gang of Four] Design pattern learning --Prototype
GoF design pattern from the problem 1. Generation
Learn the design pattern "Iterator" in Python
[Gang of Four] Design pattern learning --Memento
[Gang of Four] Design pattern learning --State
[Gang of Four] Design pattern learning --Interpreter
[Gang of Four] Design pattern learning --Builder
Learn the design pattern "Strategy" in Python
[Gang of Four] Design pattern learning --Bridge
Learn the design pattern "Composite" in Python
Learn the design pattern "Singleton" with Python
Learn the design pattern "State" in Python
Learn the design pattern "Adapter" in Python
[Gang of Four] Design pattern learning --Proxy
[Gang of Four] Design pattern learning --Strategy
[Gang of Four] Design pattern learning --Adapter
Learn the design pattern "Facade" with Python
[Gang of Four] Design pattern learning --Observer
[Gang of Four] Design pattern learning --Command
GoF design pattern from the problem 3. Behavior