27000 star! The most comprehensive collection of Python design patterns


[introduction]: design pattern is a summary of code design experience that is repeatedly used, known by most people, classified and catalogued. The purpose of using design patterns is to reuse code, make code easier to be understood by others and ensure code reliability.python-patternsIs a collection of design patterns implemented in Python.

brief introduction

Learned a lot of programming languages, is a good programmer? In fact, getting started is very simple, but real mastery requires not only writing simple programs like “Hello world”, but also skillfully applying and solving various problems. On the road of mastery, design pattern is a knowledge we will contact and need to master.

Design pattern is the solution to the general problems faced by software developers in the process of software development. These solutions are summarized by many software developers after a long period of time and mistakes. It is the cornerstone of software engineering, just like a brick of a building.

At present, the design pattern books we buy on the market are basically implemented in Java language, which is not very friendly to Python users, butpython-patternsIt just fills this gap.

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

27000 star! The most comprehensive collection of Python design patterns

Monster tried the strategy design pattern that he often used. The code in repo is very simple. It can be applied to his own project with a little change, which is very easy to use.

Supported design patterns

Create pattern

  • Abstract_factory
  • Singleton mode (Brog)
  • Builder mode (builder)
  • Factory mode
  • Lazy_evaluation
  • Object pool mode (pool)
  • Prototype

Structural model

  • Layer 3 mode (3-tier)
  • Adapter mode
  • Bridge mode
  • Composite mode
  • Decorator mode
  • Appearance mode (facade)
  • Flyweight mode
  • Front_controller mode
  • MVC mode (MVC)
  • Proxy mode

Behavioral model

  • Chain_of_responsibility
  • Catalog mode
  • Chaining_method
  • Command mode (command)
  • Iterator mode (iterator)
  • Mediator mode
  • Memo mode
  • Observer mode (observer)
  • Publish_subscribe
  • Registration mode
  • Specification mode
  • Status mode (state)
  • Strategy
  • Template mode (template)
  • Visitor mode

Testable mode

  • Dependency_injection mode

Basic mode

  • Delegation_pattern

Other modes

  • Blackboard mode
  • Graph_search
  • HSM mode (HSM)

Example of strategy mode

The monster tried it herepython-patternsExamples of policy patterns in.

The policy pattern defines a set of algorithms, encapsulates each algorithm and enables them to replace each other. The policy pattern makes each algorithm and the entity calling them independent of each other, reducing the redundancy of the code. Generally, when the algorithm strategy needs to be replaced frequently, the strategy mode can be considered. For example, the following example of order price calculation often encountered in e-commerce scenarios will use full reduction, discount, coupon and other methods to calculate the price.

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)
            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 the policy mode, you can dynamically select the price calculation strategy to be used when calculating the order price in the following way.

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

For other design pattern contents, see:

Open source outpostShare popular, interesting and practical open source projects on a daily basis. Participate in maintaining the open source technology resource library of 100000 + star, including python, Java, C / C + +, go, JS, CSS, node.js, PHP,. Net, etc.