Using Python to implement the Template method pattern pattern
The Template method pattern pattern is a behavior design pattern, which defines the skeleton of an algorithm in an operation and delays some steps to subclasses. In Python, we can implement the Template method pattern pattern through inheritance and rewriting methods.
The following is a complete sample code for implementing the Template method pattern mode in Python:
python
#Define an abstract base class
from abc import ABCMeta, abstractmethod
class AbstractClass(metaclass=ABCMeta):
#Define Template method pattern
def template_method(self):
self.hook()
self.primitive_operation_1()
self.primitive_operation_2()
#Define hook methods, subclasses can selectively override
def hook(self):
pass
#Defining abstract methods requires subclass implementation
@abstractmethod
def primitive_operation_1(self):
pass
@abstractmethod
def primitive_operation_2(self):
pass
#Implement specific subclasses
class ConcreteClass1(AbstractClass):
def primitive_operation_1(self):
Print ("Operation 1 of specific subclass 1")
def primitive_operation_2(self):
Print ("Operation 2 of specific subclass 1")
class ConcreteClass2(AbstractClass):
def primitive_operation_1(self):
Print ("Operation 1 of specific subclass 2")
def primitive_operation_2(self):
Print ("Operation 2 of specific subclass 2")
#Use specific subclasses
def main():
concrete_class1 = ConcreteClass1()
concrete_class1.template_method()
concrete_class2 = ConcreteClass2()
concrete_class2.template_method()
if __name__ == '__main__':
main()
In this example, we define an abstract base class' AbstractClass', which contains a Template method pattern 'template_ Method 'and two abstract methods' primitive'_ Operation_ 1 'and' primary '_ Operation_ 2 `. The specific subclasses' ConcreteClass1 'and' ConcreteClass2 'inherit from' AbstractClass' and implement these two abstract methods.
In 'template'_ In method ', the hook method' hook 'was first called, and then the' primitive 'was executed in a fixed order_ Operation_ 1 'and' primary '_ Operation_ 2 `. Subclasses can selectively override hook methods, but must implement abstract methods.
In the 'main' function, we create instances of specific subclasses and call 'template'_ Method 'to use the Template method pattern mode. Running the code will output:
Operation 1 of specific subclass 1
Operation 2 for specific subclass 1
Operation 1 of specific subclass 2
Operation 2 for specific subclass 2
This shows that the Template method pattern pattern successfully separates the implementation of general algorithms from the implementation of specific subclasses.