from threading import Lock
from functools import wraps
def (func):
func.__lock__ = Lock()
def acquire_lock(*args, **kwargs):
with func.__lock__:
return func(*args, **kwargs)
return acquire_lock
class Singleton1(object):
"""使用new方法"""
@thread_safety
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super(Singleton1, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __repr__(self):
return "类{}的实例对象id:{}".format(self.__class__.__name__, id(self))
class Singleton2(object):
"""使用相同属性"""
_state = {}
@thread_safety
def __new__(cls, *args, **kwargs):
instance = super(Singleton2, cls).__new__(cls, *args, **kwargs)
instance.__dict__ = cls._state
return instance
def __repr__(self):
return "类{}的实例对象id:{}".format(self.__class__.__name__, id(self))
def singleton(cls):
instances = {}
@wraps(cls)
@thread_safety
def _singleton(*args, **kwargs):
"""使用装饰器"""
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class Singleton3(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "类{}的实例对象id:{}".format(self.__class__.__name__, id(self))
if __name__ == '__main__':
s1 = Singleton1()
s2 = Singleton1()
s3 = Singleton2()
s3.name = "jordan"
s4 = Singleton2()
s5 = Singleton3(123)
s6 = Singleton3(456)
print(s1, s2, s1 is s2)
print(s3, s4, s3 is s4, s3.name is s4.name)
print(s5, s6, s5 is s6)
近期评论