# 饿汉式
class Singleton(object):
# 重写创建实例的__new__方法
def __new__(cls):
# 如果类没有实例属性,进行实例化,否则返回实例
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
饿汉式在创建的时候就会生成实例
# 懒汉式
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