This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
'''
模板方法模式(Template Method)
定义算法的骨架,而将一些步骤延迟到子类中实现。
'''
fromabcimportABC,abstractmethod
classAbstractClass(ABC):
deftemplate_method(self):
# 这是一个模板方法,它定义了一个算法的骨架
self.base_operation1()
self.required_operations1()
self.base_operation2()
self.hook1()
self.required_operations2()
self.base_operation3()
self.hook2()
@abstractmethod
defbase_operation1(self):
pass
@abstractmethod
defbase_operation2(self):
pass
@abstractmethod
defbase_operation3(self):
pass
@abstractmethod
defrequired_operations1(self):
pass
@abstractmethod
defrequired_operations2(self):
pass
defhook1(self):
pass# 钩子操作,子类可以选择是否覆盖
defhook2(self):
pass# 另一个钩子操作
classConcreteClass(AbstractClass):
defbase_operation1(self):
print("AbstractClass says: I am doing the bulk of the work")
defbase_operation2(self):
print("AbstractClass says: But I let subclasses override some operations")
defbase_operation3(self):
print("AbstractClass says: But I am doing the bulk of the work anyway")