Python Implementation of Design Pattern Notes


Design pattern learning

1. Decorator mode

This is introduced in my notes.

2. Factory model

author: liibn
Not completed, to be updated

3. singleton pattern

Ensure that at most one instance of an object exists. If there are multiple statements that create an instance, only the first one will actually create an instance, and the following statements will return the instance created for the first time.
Suitable scenario:

  • The creation of some instances consumes system resources.
  • Scenarios with high security requirements, such as bank’s modification of balance business.

Python is simply implemented using decorators, which does not consider multithreading and is not perfect.

# 单例模式装饰器
def Singleton(cls):
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]
    return _singleton
class A:
    def __init__(self, x):
        self.x = x

Test the finished decorator

# 实例化
a_one = A('one')
a_two = A('two')
a_three = A('three')
# 打印实例的地址
print(a_one, a_two, a_three, sep='\n')
# 比较三个引用是否相同
print(a_one is a_two is a_three)

The output is as follows:

<__main__.A object at 0x000001FB17894D68>
<__main__.A object at 0x000001FB17894D68>
<__main__.A object at 0x000001FB17894D68>

Herea_one,a_two,a_threeThree references point to the same instance.
If we do not use singleton pattern, then three different instances will be created. Then comment out@SingletonRun the code again with the following output:

<__main__.A object at 0x000001D772F24DA0>
<__main__.A object at 0x000001D772F24EB8>
<__main__.A object at 0x000001D772F2D518>