python中单例模式

设计模式

  • 设计模式 是 前人工作的总结和提炼,通常,被人们广泛流传的设计模式都是针对 某一特定问题 的成熟的解决方案 使用 设计模式
  • 是为了可重用代码、让代码更容易被他人理解、保证代码可靠性

单例设计模式

  • 目的 —— 让 类 创建的对象,在系统中 只有 唯一的一个实例
  • 每一次执行 类名() 返回的对象,内存地址是相同的

单例设计模式的应用场景

  • 音乐播放 对象
  • 回收站 对象
  • 打印机 对象

这里写图片描述

class Singleton(object):
    __inited = None
    def __new__(cls, *args, **kw):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if Singleton.__inited:
            return
        print("初始化")
        Singleton.__inited=True

class MyClass(Singleton):
    a = 1


one = MyClass()
print(one)
two = MyClass()
print(two)

执行结果如下:

初始化
<__main__.MyClass object at 0x7f84924bfd68>
<__main__.MyClass object at 0x7f84924bfd68>

猜你喜欢

转载自blog.csdn.net/weixin_40612082/article/details/81460583
今日推荐