直接上代码:
第一种使用函数装饰器实现并且使用锁保证线程安全:
#不使用锁实现
def SingleInstance(cls):
def new(cls,*args,**kwargs):
if not hasattr(cls,'instance'):
cls.instance= object.__new__(cls)
return cls.instance
cls.__new__=new
return cls
# 使用锁实现,确保线程安全
from multiprocessing import Lock
def SingleInstance(cls):
cls.__lock__ = Lock()
def new(cls,*args,**kwargs):
cls.__lock__.acquire()
try:
if not hasattr(cls,'instance'):
cls.instance= object.__new__(cls)
return cls.instance
finally:
cls.__lock__.release()
cls.__new__=new
return cls
#使用类实现
class SingleInstance:
def __init__(self,lock=None):
self.lock=lock or Lock()
def __call__(self,cls):
def new(cls, *args, **kwargs):
self.lock.acquire()
try:
if not hasattr(cls, 'instance'):
cls.instance = object.__new__(cls)
return cls.instance
finally:
self.lock.release()
cls.__new__ = new
return cls
使用方法 @SingleInstance
@SingleInstance
class A:
pass
第二种使用类实现装饰器:
class SingleInstance:
def __init__(self,*args,**kwargs):
self.arg=args
self.kwargs=kwargs
def __call__(self, cls):
def new(cls):
if not hasattr(cls, 'instance'):
cls.instance = object.__new__(cls)
return cls.instance
cls.__new__ = new
return cls
使用方法 @SingleInstance(*args,**kwargs)
@SingleInstance(*args,**kwargs)
class A:
pass
第三种使用元类实现装饰器:
class Meta(type):
def __call__(self, cls, *args, **kwargs):
def new(cls, *args, **kwargs):
if not hasattr(cls, 'instance'):
cls.instance = object.__new__(cls)
return cls.instance
cls.__new__ = new
return cls
class SingleInstance(metaclass=Meta):
pass
使用方法 @SingleInstance
@SingleInstance
class A:
pass