单例模式(Singleton Pattern)是一种常用的软件设计模式。主要目的是确保某一个类只有一个实例存在。
所以适用于类实例在__init__
方法中不含有初始化参数的情况。
实现方式
__new__
实现
class Single:
_instance = {}
def __new__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super().__new__(cls, *args, **kwargs)
return cls._instance[cls]
def say(self, a, b):
print(a + b)
c1 = Single()
c2 = Single()
print(id(c1))
print(id(c2))
print(c1 is c2)
print(c1.say(1, 2) is c2.say(1, 2))
函数装饰器实现
def singleton_func(cls):
_instance = {}
def inner(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return inner
@singleton_func
class Cls02:
def say(self, a, b):
print(a+b)
cls1 = Cls02()
cls2 = Cls02()
print(id(cls1) == id(cls2))
cls1.say(1, 2)
metaclass 实现
class SingletonCall(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Cls4(metaclass=SingletonCall):
def add(self, a, b):
return a + b
p1 = Cls4()
p2 = Cls4()
print(id(p1) == id(p2))
print(p2.add(1, 2) is p1.add(1, 2))
类装饰器实现
class SingletonCls:
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(*args, **kwargs)
return self._instance[self._cls]
@SingletonCls
class Cls2(object):
pass
cls1 = Cls2()
cls2 = Cls2()
print(id(cls1) == id(cls2))