单例模式的python实现

1、使用装饰器

def singleton(cls):
    _instance = {}

    def _singleton(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]

    return _singleton

@singleton
class A(object):
    def __init__(self, x):
        self.x = x

assert id(A(1)) == id(A(2))

2、类内实现,通过定义get_singleton函数+非线程安全
class Singleton(object):
    def __init__(self,*args,**kwargs):
        pass

    @classmethod
    def get_instance(cls, *args, **kwargs):
        if not hasattr(Singleton, '_instance'):
            Singleton._instance = Singleton(*args, **kwargs)
        return Singleton._instance

3、类内实现,通过定义__new__函数+线程安全
import threading

class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self, *args, **kwargs):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with Singleton._instance_lock:
                if not hasattr(cls, '_instance'):
                    Singleton._instance = super().__new__(cls)
        return Singleton._instance

def task(arg):
    obj = Singleton()

for i in range(10):
    t = threading.Thread(target=task, args=[i, ])
    t.start()
 
原文地址:https://www.cnblogs.com/zcsh/p/14246191.html