为了账号安全,请及时绑定邮箱和手机立即绑定

python-patterns:python风格的设计模式

标签:
Python

首先,从策略模式说起

在大多数的编程语言中,策略模式实现是这样的:
首先创建一个基础策略(通过接口或抽象类),然后创建若干子类继承这个基础策略(见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 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消