def singleton(cls, *args, **kwargs):
instances = {}
def inner(cls, *args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return inner
@singleton
class Test1:
pass
# 推荐使用这种 简单好用 线程安全
# ===========================================================
import threading
class Singleton:
def __init__(self, cls):
self.__cls = cls
self.__instance = None
self._lock = threading.Lock()
def __call__(self, *args, **kwargs):
self._lock.acquire()
if self.__instance is None:
self.__instance = self.__cls(*args, **kwargs)
self._lock.release()
return self.__instance
@Singleton
class Test2:
pass
# 继承时的执行顺序 base new -> son new -> son init. new 相当于构造方法,init相当于实例后再初始化 先执行父类的new 就好比先是人再是学生
# ==============================================================
class SingleBase(object):
instance = None
def __new__(cls, *args, **kwargs):
# if not instance:
# instance = cls.__new__(*args, **kwargs):
# return instance
if cls.instance is None:
cls.instance = object.__new__(cls)
return cls.instance
def __init__(self):
pass
class Test3(SingleBase):
def __init__(self, name):
self._name = name
def get_name(self):
return self._name
# meta 这个我还不是很懂
# =====================================================
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Test4(metaclass=MetaSingleton):
def __init__(self):
pass
if __name__ == '__main__':
t1 = Test3('jwang')
t2 = Test3('hello')
print(id(t1))
print(id(t2))
print(t1.get_name())
print(t2.get_name())
test3 = Test4()
test4 = Test4()
print(id(test3) == id(test4))