单例模式

所谓的单例模式,就是对一个类做一定的特殊处理,使得在实例化这个类的对象的时候内存中只放着一份对象。python单例模式的实现有很多种方式,这里只列出本人常用的两种方式,其中第二种是Django源码使用的方式

new

from threading import Lock
from threading import Thread, current_thread
import time
lock = Lock()

class SingleModel(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        with lock:
            if not cls.__instance:
                cls.__instance = object.__new__(cls, *args, **kwargs)
            return cls.__instance
        # with lock:
        #     if not cls.__instance:
        #         time.sleep(1)
        #         cls.__instance = object.__new__(cls, *args, **kwargs)
        #     return cls.__instance
            
        # if not cls.__instance:
        #     time.sleep(1)
        #     cls.__instance = object.__new__(cls, *args, **kwargs)
        # return cls.__instance

def task1():
    s = SingleModel()
    print(current_thread().name, id(s))

def task2():
    s = SingleModel()
    print(current_thread().name, id(s))

if __name__ == '__main__':
    t1 = Thread(target=task1, name='t1')
    t2 = Thread(target=task1, name='t2')
    t1.start()
    t2.start()

new 这种方式在每次实例化的时候,真实的创建对象的object.new 只会被调用一次

模块导入

虽然有很多py文件,但是真正执行的时候只是一个程序,或者说只有一个入口的py文件,其他都是相互导入,在import func的时候会执行from test import single_obj,但是test模块已经导入过一次了,不会重复导入,拿single_obj就从pyc文件去拿了

原文地址:https://www.cnblogs.com/longyunfeigu/p/9504782.html