27000 stars! The most comprehensive collection of Python design patterns

Open source outpost 2021-02-20 17:21:28
stars comprehensive collection python design


【 Introduction 】: A design pattern is a set that is used repeatedly 、 Most people know that 、 Catalogued 、 Summary of code design experience . Design patterns are used for reusable code 、 Make code easier for others to understand 、 Ensure code reliability .python-patterns Is the use python Implement a collection of design patterns .

brief introduction

Learned a lot of programming languages , Is he a good programmer ? in fact , The introduction is very simple , But real mastery doesn't just need to be able to write simple analogies “Hello World” The program , Also need to be proficient in application , And solve all kinds of problems . On the road to mastery , Design pattern is a knowledge that we must contact and master .

Design patterns are the solution to the general problems that software developers face in the process of software development , These solutions are summed up by many software developers after a long period of time and mistakes , It's the cornerstone of software engineering , It's like bricks and stones in a building .

Currently on the market , The design patterns book we bought , It's basically using Java The realization of language , about Python The users of the language are not very friendly , and python-patterns It just fills the gap .

The address of this open source project is :https://github.com/faif/pytho...

Monster tried the strategy design pattern that he often used ,repo The code in is very simple , A little change can be applied to your own project , It's very easy to use .

Supported design patterns

Create pattern

  • Abstract factory pattern (abstract_factory)
  • The singleton pattern (brog)
  • Builder pattern (builder)
  • Factory mode (factory)
  • Inert evaluation model (lazy_evaluation)
  • Object pool mode (pool)
  • Archetypal model (prototype)

Structural mode

  • 3 Layer pattern (3-tier)
  • Adapter pattern (adapter)
  • Bridging mode (bridge)
  • Portfolio model (composite)
  • Decorator mode (decorator)
  • Appearance mode (facade)
  • The flyweight pattern (flyweight)
  • Front end controller mode (front_controller)
  • MVC Pattern (mvc)
  • The proxy pattern (proxy)

Behavioral patterns

  • The chain of responsibility model (chain_of_responsibility)
  • Directory mode (catelog)
  • Method chain model (chaining_method)
  • Command mode (command)
  • Iterator pattern (iterator)
  • Intermediary model (mediator)
  • Memo mode (memento)
  • Observer mode (observer)
  • Publish subscribe mode (publish_subscribe)
  • Registration mode (registry)
  • Specification mode (specification)
  • The state pattern (state)
  • The strategy pattern (strategy)
  • Template pattern (template)
  • Visitor mode (visitor)

Testable mode

  • Dependency injection pattern (dependency_injection)

The basic model

  • Delegate pattern (delegation_pattern)

Other modes

  • Blackboard mode (blackboard)
  • Graph search mode (graph_search)
  • hsm Pattern (hsm)

Examples of policy patterns

Here the monster tried python-patterns Example of the strategy pattern in .

The policy pattern defines a set of algorithms , Encapsulate every algorithm , And they can replace each other . The policy pattern makes each algorithm and the entity that calls them independent of each other , Reduced code redundancy . Generally, when the algorithm strategy needs to be replaced frequently , Consider the policy pattern . For example, the following example of order price calculation is often encountered in e-commerce scenarios , The full reduction will be used in calculating the price 、 Discount 、 Coupons, etc .

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

After using policy mode , It can be done as follows , When calculating the price of an order , Dynamic selection needs to use the price calculation strategy .

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()

Other design pattern content , Please see the :
https://github.com/faif/pytho...

Open source outpost Everyday sharing is hot 、 Interesting and practical open source projects . Participate in maintenance 10 ten thousand + Star Open source technology repository for , Include :Python、Java、C/C++、Go、JS、CSS、Node.js、PHP、.NET etc. .
版权声明
本文为[Open source outpost]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210220172055481W.html

  1. Realization of color space conversion between RGB and lab by Python
  2. Download MP4 from Python
  3. CONDA changes Python version
  4. Python writes multiple lines
  5. Convert Python numpy to string
  6. Python fastapi的简单使用
  7. 使用Python+Appuim 清理微信
  8. Simple use of Python fastapi
  9. Clean up wechat with Python + appuim
  10. 4个玩游戏就能学会Python的网站
  11. Four games to learn Python website
  12. 成功解决利用pandas的read_csv函数读取csv文件的时候出现中文乱码问题
  13. Python之pandas:pandas的get_dummies函数简介(将分类变量转为哑变量)及其使用方法之详细攻略
  14. Python之category-encoders:category-encoders库的简介、安装、使用方法之详细攻略
  15. ML之FE:pandas库中数据分析利器之groupby分组函数、agg聚合函数、同时使用groupby与agg函数组合案例之详细攻略
  16. Python之Pandas:利用pandas实现行数据添加,即将字典格式的数据,按照行数据循环添加到dataframe中
  17. Successfully solve the read problem using Panda_ The Chinese garbled code appears when the CSV function reads the CSV file
  18. Panda of Python: get of Panda_ Introduction to dummies function (converting classified variables into dummy variables) and detailed introduction to its usage
  19. Python's category encoders: introduction, installation and usage of the category encoders Library
  20. Fe of mL: detailed introduction of groupby group function, AGG aggregate function, and the combination of groupby and AGG function in pandas database
  21. Python pandas: using pandas to add row data, that is, adding dictionary data to dataframe according to row data cycle
  22. Python:将Flask测试应用部署到Deta
  23. Python:OAuth2第三方登录之Github
  24. Python:使用pydantic库进行数据校验
  25. Python:免费IP归属地查询接口
  26. Python:使用user-agents库解析浏览器信息
  27. Python:cached_property缓存对象的属性
  28. Python:打包配置文件 setup.py 详解
  29. Python:ORM(Object Relational Mapper)模块汇总整理
  30. Python:datetime时间UTC时间转东八区
  31. Python: deploying flash test application to deta
  32. Python: oauth2 GitHub for third party login
  33. Python: using pydantic library for data verification
  34. Python: free IP home location query interface
  35. Python: parsing browser information using user agents Library
  36. Python:cached_ Property to cache the properties of an object
  37. Python: packaging configuration files setup.py Detailed explanation
  38. Python: ORM (object relational mapper) module summary
  39. Python: datetime, UTC, turn to District 8, East
  40. python tkinter 将某一目录下的所有图片插入到docx文件中
  41. Python Tkinter inserts all the pictures in a directory into the docx file
  42. 解决忽略VScode中Python插件pylint报错的问题
  43. To solve the problem of ignoring the error of Python plug-in in vscode
  44. python 毫秒级时间,时间戳转换
  45. Python millisecond time, timestamp conversion
  46. python try except 出现异常时,except 中如何返回异常的信息字符串
  47. When an exception occurs in Python try except, how to return the exception information string in except
  48. 手机最强Python编程神器,在手机上运行Python
  49. The strongest Python Programming artifact on mobile phones, running Python on mobile phones
  50. 2021年Python程序员薪资待遇如何?
  51. 「python安装」Windows上安装和创建python开发环境
  52. What is the salary of Python programmers in 2021?
  53. "Python installation" to install and create a python development environment on Windows
  54. python解决组合问题
  55. Python to solve the problem of composition
  56. Python中的Lasso回归之最小角算法LARS
  57. Lars, the least angle algorithm of lasso regression in Python
  58. 利用python提取网站曲线图数据
  59. Using Python to extract website graph data
  60. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)