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

首先,从策略模式说起

在大多数的编程语言中,策略模式实现是这样的:
首先创建一个基础策略(通过接口或抽象类),然后创建若干子类继承这个基础策略(见wikipedia),再次,balabala……

然而,python中用一个类就可以实现策略模式了,正如下面例子中实现的这样,将函数注入这个类的实例即可:

import types

class 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

最后,我想打个广告,要是反响不好以后就不提了,标题也变小了……

我在简书上创建了专题『Github 上有趣的资源』,本文也收录于此,如果大家对Github的主题有啥可以分享,欢迎投稿~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容