首先,从策略模式说起
在大多数的编程语言中,策略模式实现是这样的:
首先创建一个基础策略(通过接口或抽象类),然后创建若干子类继承这个基础策略(见wikipedia),再次,balabala……
然而,python中用一个类就可以实现策略模式了,正如下面例子中实现的这样,将函数注入这个类的实例即可:
import typesclass StrategyExample: def __init__(self, func=None): self.name = 'Strategy Example 0' if func is not None: self.execute = types.MethodType(func, self) def execute(self): print(self.name)def execute_replacement1(self): print(self.name + ' from execute 1')def execute_replacement2(self): print(self.name + ' from execute 2')if __name__ == '__main__': strat0 = StrategyExample() strat1 = StrategyExample(execute_replacement1) strat1.name = 'Strategy Example 1' strat2 = StrategyExample(execute_replacement2) strat2.name = 'Strategy Example 2' strat0.execute() strat1.execute() strat2.execute()### OUTPUT #### Strategy Example 0# Strategy Example 1 from execute 1# Strategy Example 2 from execute 2
这种方式,既体现了策略模式的精髓,也很好的与python结合,对此,Gevin表示:awesome!
然后,下面才是本文重点
如此巧妙的策略模式的实现,不是我研究出来的,而是我发现的:
本段代码其实来源于Github,有一个叫做『python-patterns』的repo,这里收集了所有设计模式的python版实现,我谓之pythonic design pattern,大家可以去看看,尤其推荐各位做后台的同学,即便不用python,也可以开拓思路,不妨说是Gevin介绍来的 :p
作者:Gevin
链接:https://www.jianshu.com/p/f277a3de97ae
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優質文章
正在加載中
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦