Template method pattern , Define an algorithm or process , Some links are designed to be externally variable , Instantiate an entity with an idea similar to a template , You can fill the template with different contents ;
Under the template idea , The overall framework of the entity is determined , He is a template , But the content under the template is variable , So as to realize the dynamic update process or algorithm .
The template method pattern is somewhat similar to the builder pattern . But the builder pattern is to separate the construction and representation of objects , The same build generates different presentation objects ; The template method is to postpone some links in the defined algorithm or process to subclasses to realize the variable function of the algorithm or process , This is the essential difference between the two .
Entity role :
import abc
from time import sleep
# abstract class
class DriveCar(metaclass=abc.ABCMeta):
@abc.abstractmethod
def OpenDoor(self): # Declare atomic operations
pass
@abc.abstractmethod
def PullHandbrake(self): # Declare atomic operations
pass
@abc.abstractmethod
def StartUp(self): # Declare atomic operations
pass
@abc.abstractmethod
def OnTheWay(self): # Declare atomic operations
pass
# Template operation , Implement... In an abstract class .
def Drive(self):
self.OpenDoor()
self.PullHandbrake()
self.StartUp()
while True:
try:
self.OnTheWay()
sleep(1)
except KeyboardInterrupt:
break
# concrete class
class XiaoMingDriveCar(DriveCar):
def __init__(self, music):
self.music = music
def OpenDoor(self): # Atomic operation
print(" Get your ass up and open the door !")
def PullHandbrake(self): # Atomic operation
print(" Raise your orchid finger and pull down the handbrake !")
def StartUp(self): # Atomic operation
print(" Release the clutch , Start slowly !")
def OnTheWay(self): # Atomic operation
print(f" Driving ...“{
self.music}”")
if __name__ == "__main__":
music = " Pleasant Sheep , Beautiful sheep , lazy sheep ..."
xiaoming = XiaoMingDriveCar(music)
xiaoming.Drive()