当前位置: 首页 > news >正文

单例模式介绍

【一】为什么要单例模式

单例设计模式:

  • 一个类只允许创建一个对象(或者实例),那这个类就是一个单例类,这种设计模式就叫作单例设计模式,简称单例模式。

  • 当一个类的功能比较单一,只需要一个实例对象就可以完成需求时,就可以使用单例模式来节省内存资源。

【二】如何实现一个单例

  • 要实现一个单例,我们需要知道要重点关注的点是哪些?

    • 考虑对象创建时的线程安全问题

    • 考虑是否支持延迟加载

    • 考虑获取实例的性能是否高(是否加锁)

  • 在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(metaclass=MyType):...
​
​
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
http://www.lryc.cn/news/350378.html

相关文章:

  • Facebook企业户/在Facebook上做推广有什么好处?
  • Go GORM实战(二) | 数据库连接的N种方式
  • Cocos Creator 2D Mask与Layout 使用详解
  • 项目-坦克大战
  • 代码随想录算法训练营第二十九天| LeetCode491.递增子序列* 、LeetCode46.全排列*、LeetCode47.全排列 II
  • 基于SpringBoot设计模式之开端
  • tensorflow实现二分类
  • 简化路径[中等]
  • 记一次若依项目组装树型结构数据的效率优化
  • 秒杀系统之系统优化
  • 【介绍下Python多线程,什么是Python多线程】
  • FPGA相关论文阅读
  • 瑞芯微RK3588驱动设计之DVP并口摄像头2
  • 安卓手机APP开发__支持64位的架构
  • Foxmail使用经验总结
  • 信息系统项目管理师0601:项目立项管理 — 考点总结(可直接理解记忆)
  • 实验三:机器学习1.0
  • Vue 3 + Vite项目实战:常见问题与解决方案全解析
  • 飞天使-k8s知识点31-rancher的正确打开方式
  • Vue.component v2v3注册(局部与全局)组件使用详解
  • HNU-算法设计与分析-作业5
  • 基础之音视频2
  • 两小时看完花书(深度学习入门篇)
  • 21【Aseprite 作图】画白菜
  • 2024.05.15 [AI开发配环境]个人使用最新版远程服务器配环境大纲:docker、云盘、ssh、conda等
  • opencv 轮廓区域检测
  • 2024-5-16
  • IT行业的现状与未来:技术创新引领时代变革
  • Redis分布式锁【简单版】
  • 18.Blender 渲染工程、打光方法及HDR贴图导入