单例分为:懒汉和饿汉模式
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
文章介绍了Python中实现单例模式的两种常见方式:饿汉模式和懒汉模式。饿汉模式通过装饰器和基类实现,确保类在初始化时即创建单例。懒汉模式则在首次调用`get_instance`类方法时才创建实例。
378





