专业介绍:
指一个类只有一个实例,且该类能自行创建这个实例的一种模式。
通俗介绍:
一个类,我们可以反复创建它的实例,但是,创建N次最终得到的也是同一个实例,占用的资源大小是固定的,这就叫单例模式。
例如Windows上很多对象都是单例模式,比如winows的任务管理器,回收站,文件系统,线程池等待,如果他们可以被创建出多个实例,系统肯定满地bug。
代码:
# 单例模式
# ---------- 装饰器实现单例 ------------
def single(func_or_cls):
"""适用于函数、类的单例创建"""
def _wrap(*args, **kw):
if not hasattr(func_or_cls, '_instance'): # `_instance` 为自定义
func_or_cls._instance = func_or_cls(*args, **kw)
return func_or_cls._instance
return _wrap
@single
class God:
def __init__(self):
print('I am only God!')
# ---------- 使用 __new__()实现单例 ------------
class SingleGod:
def __init__(self):
"""如果已经有一个实例,这里要判断不再初始化"""
if getattr(SingleGod, '_inited') is True:
return
print('I am only God!')
def __new__(cls, *args, **kwargs):
"""与具体类耦合,不够方便"""
if not hasattr(cls, '_ins'):
cls._ins = object.__new__(cls)
cls._inited = False
else:
cls._inited = True
return cls._ins
if __name__ == '__main__':
God_1 = God()
God_2 = God()
print(God_1 is God_2)
'''
>>output
I am only God!
True
'''
God_3 = SingleGod()
God_4 = SingleGod()
print(God_3 is God_4)
'''
>>output
I am only God!
True
'''
说明:单例模式绝对是众多设计模式中最常用的模式了,在平常的开发中经常会用到,比如由你实现一个数据库连接类,你一定不希望使用者在代码中到处创建数据库连接,而是调用统一创建的连接实例。依靠口头约束往往是不可靠的,一旦出现异常就会导致比较严重的生产事故,所以需要我们在设计之初就要做好限制。