单例模式
单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
实现方式:
1.使用模块
Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc
文件,当第二次导入时,就会直接加载 .pyc
文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:
mysingleton.py
class Singleton(object):
def foo(self):
pass
singleton = Singleton()
将上面的代码保存在文件 mysingleton.py
中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象
from a import singleton
2.使用装饰器
简单装饰器
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 A:
a = 1
def __init__(self, x =0):
self.x = x
a = A(1)
b = A(3)
print(a.x, b.x)
"""
result
1 1
"""
类装饰器
class C_Singleton:
def __init__(self, cls):
self._cls = cls
self._instance = {}
pass
def __call__(self, *args, **kwargs):
if self._cls not in self._instance:
self._instance[self._cls] = self._cls()
return self._instance[self._cls]
@C_Singleton
class B:
b = 1
def __init__(self, x =0):
self.x = x
"""
result
b1= B()
b2 = B()
print(id(b1) ==id(b2), '1212')
"""
3.new关键字
# new关键字
class Single:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Single, cls).__new__(cls, *args, **kwargs)
return cls._instance
single1 = Single()
single2 = Single()
print(id(single1) == id(single2))
4.metaclass
# metaclass
class Singleton(type):
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance[cls]
class C(metaclass=Singleton):
pass
cls1 = C()
cls2 = C()
print(id(cls1) == id(cls2))