程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python design pattern behavioral pattern template method pattern

編輯:Python

Catalog

List of articles

  • Catalog
  • Template method pattern
  • Application scenarios
  • Code example

Template method pattern

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 .

Application scenarios

Code example

Entity role :

  • abstract class (AbstractClass): Define abstract atomic operations ; Implement a template method as the skeleton of the algorithm .
  • concrete class (ConcreteClass): Atomic operation .
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()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved