python 模板方法模式

这里的模板和文档模板的意思一致, 即定义一个类的骨架, 这里主要是用于控制函数执行顺序, 但不同的操作交给子类去实现.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from abc import ABC, abstractmethod

class Fishing(ABC):
"""钓鱼模板基类与抽象方法"""
@abstractmethod
def prepare_bait(self):
pass

@abstractmethod
def goto_riverbank(self):
pass

@abstractmethod
def find_location(self):
pass

def __call__(self):
# 直接使用 __call__ , 不再定义其他方法
self.prepare_bait()
self.goto_riverbank()
self.find_location()
print('start fishing')


class LeoFishing(Fishing):
"""子类1的实现"""
def prepare_bait(self):
print('Leo: buy it online')

def goto_riverbank(self):
print('Leo: by driving')

def find_location(self):
print('Leo: select an island')

class RajFishing(Fishing):
"""子类1的实现"""
def prepare_bait(self):
print('Raj: buy it from a store')

def goto_riverbank(self):
print('Raj: by biking')

def find_location(self):
print('Raj: select a boat')

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
>>> l = LeoFishing()
>>> l()
Leo: buy it online
Leo: by driving
Leo: select an island
start fishing
>>> r = RajFishing()
>>> r()
Raj: buy it from a store
Raj: by biking
Raj: select a boat
start fishing
>>>

模板方法模式比较简单易懂, 主要是基类将复杂流程总结在一个方法中, 再由子类对这些流程进行不同的实现.