【导语】:设计模式是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易地被他人理解、保证代码可靠性。python-patterns 则是使用 python 实现设计模式的集合。 简介学会了很多门编程语言,就是一个好程序员了吗?事实上,入门很简单,但真正的精通不仅需要会写出简单的类似“Hello World”的程序,还需要熟练应用,并解决各种问题。在精通的道路上,设计模式是我们一定会接触并需要掌握的一个知识。 设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案,这些解决方案是众多软件开发人员经过相当长的一段时间和错误总结出来的,它是软件工程的基石,如同大厦的一块块砖石一样。 目前市面上,我们买到的设计模式的书,基本是用 Java 语言实现的,对于Python 语言的用户不是很友好,而python-patterns 恰好填补了这个空白。 这个开源项目的地址是:https://github.com/faif/python-patterns 怪兽试用了自己经常用的策略设计模式,repo 里的代码很简洁,稍微改改就可以应用到自己的项目里,十分好用。 支持的设计模式创建型模式 结构型模式 - 前端控制器模式(front_controller)
行为型模式 - 责任链模式(chain_of_responsibility)
- 发布订阅模式(publish_subscribe)
可测试型模式 - 依赖注入模式(dependency_injection)
基础模式 其他模式 策略模式举例在这里怪兽试用了python-patterns 里的策略模式示例。 策略模式定义了一组算法,将每个算法都封装起来,并使他们之间可以互相替换。策略模式使得每个算法和调用他们的实体彼此独立,减少了代码的冗余。一般当算法策略需要经常被替换时,可以考虑策略模式。比如下面在电商场景里会经常碰到的订单价格计算的例子,计算价格时会用到满减、打折、优惠券等方式。 class Order: def __init__(self, price, discount_strategy=None): self.price = price self.discount_strategy = discount_strategy
def price_after_discount(self): if self.discount_strategy: discount = self.discount_strategy(self) else: discount = 0 return self.price - discount
def __repr__(self): fmt = '<Price: {}, price after discount: {}>' return fmt.format(self.price, self.price_after_discount())
def ten_percent_discount(order): return order.price * 0.10
def on_sale_discount(order): return order.price * 0.25 + 20
在使用策略模式后,可按如下方式,在计算订单价格时,动态的选择需要使用的价格计算策略。 def main(): ''' >>> Order(100) <Price: 100, price after discount: 100> >>> Order(100, discount_strategy=ten_percent_discount) <Price: 100, price after discount: 90.0> >>> Order(1000, discount_strategy=on_sale_discount) <Price: 1000, price after discount: 730.0> '''
if __name__ == '__main__': import doctest doctest.testmod()
其他设计模式内容,请参见: https://github.com/faif/python-patterns - EOF -
|