单例模式介绍

【一】为什么要单例模式

单例设计模式:

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

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

【二】如何实现一个单例

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

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

    • 考虑是否支持延迟加载

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

  • 在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 初始值是none
        cls.instance = None
        super().__init__(class_name,class_bases,class_name_space)
​
    def __call__(self, *args, **kwargs):
        obj = super().__call__(*args,**kwargs)
        # 判断 只要有就返回他不创建,没有就创建再返回
        if not self.instance:
            self.instance =obj
        return 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
        # 进行判断是否有cls
        if 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

相关推荐

  1. 模式介绍

    2024-05-16 01:40:10       12 阅读
  2. 介绍模式

    2024-05-16 01:40:10       8 阅读
  3. 模式介绍

    2024-05-16 01:40:10       30 阅读
  4. 模式模板

    2024-05-16 01:40:10       18 阅读
  5. 模式【C#】

    2024-05-16 01:40:10       35 阅读
  6. python模式

    2024-05-16 01:40:10       34 阅读
  7. 模式详解

    2024-05-16 01:40:10       39 阅读
  8. 模式学习

    2024-05-16 01:40:10       27 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-16 01:40:10       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-16 01:40:10       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-16 01:40:10       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-16 01:40:10       18 阅读

热门阅读

  1. 调用外部的webservice示例

    2024-05-16 01:40:10       11 阅读
  2. 局域网路由器 交换机 ap模式

    2024-05-16 01:40:10       16 阅读
  3. Spring-Cloud-OpenFeign源码解析-02-OpenFeign自动装配

    2024-05-16 01:40:10       12 阅读
  4. 【鱼眼+普通相机】相机标定

    2024-05-16 01:40:10       9 阅读
  5. FastAdmin菜单规则树形结构分类显示

    2024-05-16 01:40:10       9 阅读