美文网首页
python单例模式

python单例模式

作者: 转身丶即天涯 | 来源:发表于2019-09-29 13:47 被阅读0次

参考资料:
https://zhuanlan.zhihu.com/p/37534850

什么是单例模式

就是全局作用域内只有一个实例的设计模式。
常见使用场景,比如数据库的连接对象,配置文件中的变量等等。

单例模式的实现

1.使用函数装饰器
# 1. decorator
def singleton(cls):
    _instance = {}

    def wrap():
        if cls not in _instance:
            _instance[cls] = cls()

        return _instance[cls]

    return wrap


@singleton
class A(object):
    def __init__(self):
        pass
2.使用类装饰器
# 2. class decorator
class Singleton(object):
    def __init__(self, cls):
        self._cls = cls
        self._instance = {}

    def __call__(self, *args, **kwargs):
        if self._cls not in self._instance:
            self._instance[self._cls] = self._cls()

        return self._instance[self._cls]


@Singleton
class B():
    def __init__(self):
        pass
3.使用new方法
class C(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = object.__new__(cls, *args, **kwargs)

        return cls._instance

    def __init__(self):
        pass

相关文章

  • python之理解单例模式

    python之理解单例模式 1、单例模式 单例模式(Singleton Pattern)是一种常见的软件设计模式,...

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 2018-06-19 Python中的单例模式的几种实现方式的及

    转载自: Python中的单例模式的几种实现方式的及优化 单例模式 单例模式(Singleton Pattern)...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

  • 基础-单例模式

    单例模式总结-Python实现 面试里每次问设计模式,必问单例模式 来自《Python设计模式》(第2版) 1.理...

  • python单例模式

    python单例模式实现方式 使用模板 python模块是天然的单例模式(.pyc文件的存在) 使用__new__...

  • 一套完整Python经典面试题,实力派,做内容不做标题党!

    文末含Python学习资料 1:Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例...

  • Python 面向对象7: 单例模式

    一、内容 1.1、单例设计模式 1.2、__new__方法 1.3、Python 中的单例 二、单例设计模式 2....

  • Python设计模式 之 Borg模式

    Borg模式 是单例模式在python中的变种。传统单例模式在python中,存在继承兄弟类之间状态隔离的问题。 ...

网友评论

      本文标题:python单例模式

      本文链接:https://www.haomeiwen.com/subject/detyyctx.html