前言
虽然设计模式语言无关,但是语言的特性可以简化设计模式的实现。python中的一等函数(可移步上一个帖子)至关重要,使用一等函数可以简化设计模式的实现。“策略”模式就是其中一个很好的例子。
一、经典的“策略”模式
上下文:学生要准备期末考试。
策略:实现不同算法的组件共同接口,值得是学生的学习方式
具体策略:不同的学习方式:看书、刷题等等。
代码如下(示例):
class StudyWay(ABC):
@abstractmethod
def study(self):
"""抽象学习方式"""
class ReadStudyWay(StudyWay):
def study(self):
print("看书")
class DoWay(StudyWay):
def study(self):
print("做题")
class Student:
def __init__(self, study_way):
self.__study_way = study_way
def prepare_exam(self):
self.__study_way.study()
print("考试")
if __name__ == '__main__':
stu_r = Student(ReadStudyWay())
stu_d = Student(DoWay())
stu_r.prepare_exam()
stu_d.prepare_exam()
在上述示例中,每个具体策略都是一个类,而且都定义了一个方法,即study()。此外,策略实例没有属性。这种方式类似于Java的实现方式。
二、函数实现策略模式
经典的策略模式,其策略实例没有状态,看起来像是普通的函数。借助python中的一等函数就将具体策略换为普通函数。
代码如下(示例):
def read_study():
print("看书")
def do_study():
print("做题")
class Student:
def __init__(self, study_way):
self.__study_way = study_way
def prepare_exam(self):
self.__study_way()
print("考试")
if __name__ == '__main__':
stu_r = Student(read_study)
stu_d = Student(do_study)
stu_r.prepare_exam()
stu_d.prepare_exam()
上述示例,基于函数的一等特性实现了具有python特色的“策略”模式,将具体的策略换为了简单的函数,而且去掉了抽象类。