单例分为:懒汉和饿汉模式
1.1饿汉-使用装饰器
def singleton(cls):
_instance = {}
def wrapper(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return wrapper
@singleton
class Foo:
...
1.2.饿汉-使用基类
class Singleton:
_instance = {}
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
@Singleton
class Foo:
...
2.懒汉模式
class Singleton(object):
_instance = None
def __init__(self):
if not self._instance:
print('调用__init__, 实例未创建')
else:
print('调用__init__,实例已创建:', _instance)
@classmethod
def get_instance(cls):
# 调用get_instance类方法的时候才会生成Singleton实例
if not cls._instance:
cls._instance = Singleton()
return cls._instance