做网站现在什么最赚钱吗,网站 免费空间,网站建设打广告,注销网站 注销主体【一】为什么要单例模式
单例设计模式#xff1a; 一个类只允许创建一个对象#xff08;或者实例#xff09;#xff0c;那这个类就是一个单例类#xff0c;这种设计模式就叫作单例设计模式#xff0c;简称单例模式。 当一个类的功能比较单一#xff0c;只需要一个实例…【一】为什么要单例模式
单例设计模式 一个类只允许创建一个对象或者实例那这个类就是一个单例类这种设计模式就叫作单例设计模式简称单例模式。 当一个类的功能比较单一只需要一个实例对象就可以完成需求时就可以使用单例模式来节省内存资源。
【二】如何实现一个单例 要实现一个单例我们需要知道要重点关注的点是哪些 考虑对象创建时的线程安全问题 考虑是否支持延迟加载 考虑获取实例的性能是否高是否加锁 在python中我们可以使用多种方法来实现单例模式 使用模块 使用装饰器 使用类方法 基于__new__方法实现 基于元类metaclass实现
# 创建一个普通的类
class Student:...
# 实例化类得到对象 --- 类只要加 () 实例化就会产生一个全新的对象
# 查看对象 --- 发现虽然是同一个类实例化得到的对象但是对象的地址不一样
# 每次使用都要重新打开内存占用过高
stu_one Student()
print(id(stu_one)) # 1764834580640
stu_two Student()
print(id(stu_two)) # 1764834304080
单例模式的实现
# 方式一
class MyType(type):def __init__(cls,class_name,class_bases,class_name_space):# 给自己的类中加一个属性 instance 初始值是nonecls.instance Nonesuper().__init__(class_name,class_bases,class_name_space)
def __call__(self, *args, **kwargs):obj super().__call__(*args,**kwargs)# 判断 只要有就返回他不创建没有就创建再返回if not self.instance:self.instance objreturn self.instance
class Student(metaclassMyType):...
stu_one Student()
print(id(stu_one)) # 2645492891216
stu_two Student()
print(id(stu_two)) # 2645492891216
# 定制类的属性 ---》 元类 __init__
# 定制对象的属性 --- 元类 __call__
# 方式二
# 使用装饰器
# outer 接受cls类作为参数
def outer(cls):# 定义一个字典键为cls初始值为none永远存储cls的单例实例instance {cls:None}
def inner(*args, **kwargs):# 使用nonlocal关键字声明 instance变量这意味着inner函数将修改在outer函数中定义的instance变量而不是创建一个新的nonlocal instance# 进行判断是否有clsif not instance[cls]:instance[cls] cls(*args, **kwargs)return instance[cls]
return inner
outer
class Student:...
stu_one Student()
print(id(stu_one)) # 1384468577632
stu_two Student()
print(id(stu_two)) # 1384468577632