单例模式
1. 函数装饰器实现
def singleton1(cls):
_instance = {}
def inner(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls()
return _instance[cls]
return inner
@singleton1
class A(object):
def __init__(self):
pass
cls1 = A()
cls2 = A()
print(id(cls1) == id(cls2))
2. 类装饰器实现
class Singleton2(object):
def __init__(self, cls):
self._cls = cls
self._instance = {}
def __call__(self, *args, **kwargs):
if self._cls not in self._instance:
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@Singleton2
class B(object):
def __init__(self):
pass
cls3 = B()
cls4 = B()
print(id(cls3) == id(cls4))
3. 使用 new 关键字实现单例模式
class Single(object):
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
pass
single1 = Single()
single2 = Single()
print(id(single1) == id(single2))
4. 使用metaclass
实现单例模式
class Singleton3(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton3, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Cls5(metaclass=Singleton3):
pass
cls6 = Cls5()
cls7 = Cls5()
print(id(cls6) == id(cls7))