# 单例模式可以保证一个类仅有一个实例,并提供一个访问它的全局访问点。
# 适用性于当类只能有一个实例而且客户可以从一个众所周知的访问点访问它,例如访问数据库、MQ等
实现方式:
1、通过导入模块实现
2、通过装饰器实现
3、通过使用类实现
4、通过__new__方法实现
# ========== Method One:通过导入模块实现 ==========
from singleton import s as s1
from singleton import s as s2
def show_method_one():
print(s1, s2)
print(id(s1), id(s2))
print('========== Method One:通过导入模块实现 ==========')
show_method_one()
# ========== Method Two:通过装饰器实现 ==========
def singleton(cls):
# 创建一个字典用来保存类的实例对象
_instance = {}
def _singleton(*args, **kwargs):
# 先判断这个类有没有对象
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs) # 创建一个对象,并保存到字典当中
# 将实例对象返回
return _instance[cls]
return _singleton
@singleton
class Demo2(object):
a = 1
def __init__(self, x=0):
self.x = x
a1 = Demo2(1)
a2 = Demo2(2)
print('========== Method Two:通过装饰器实现 ==========')
print(id(a1), id(a2))
# ========== Method Three:通过使用类实现 ==========
class Demo3(object):
# 静态变量
_instance = None
_flag = False
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
if not Demo3._flag:
Demo3._flag = True
b1 = Demo3()
b2 = Demo3()
print('========== Method Three:通过使用类实现 ==========')
print(id(b1), id(b2))
# ========== Method Four:通过__new__ 方法实现 ==========
class Demo4:
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Demo4, cls).__new__(cls)
return cls._instance
c1 = Demo4()
c2 = Demo4()
print('========== Method Four:通过__new__ 方法实现 ==========')
print(id(c1), id(c2))