美文网首页
python单例模式

python单例模式

作者: nice生活 | 来源:发表于2018-11-06 14:10 被阅读0次

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

__new__()在__init__()之前被调用,用于生成实例对象。利用这个方法和类的属性的特点可以实现设计模式的单例模式。单例模式是指创建唯一对象,单例模式设计的类只能实例 一次

使用__new__方法


class Single:

    def __new__(cls, *args, **kw):
        if not hasattr(cls, "_instance"):
            cls._instance = super().__new__(cls, *args, **kw)
        return cls._instance


class MyClass(Single):
    a = 1


print(MycClass() == MycClass())
#true

使用元类

class Single(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class MyClass(metaclass=Single):
    a = 1

装饰器

def single(cls):
    instances = {}
    def getinstance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return getinstance

@single
class MyClass:
  ...

使用模块

# single.py
class Single(object):
    def foo(self):
        pass

my_single = Single()

# to use
from single import my_single

my_single.foo()

相关文章

  • 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/wlgfxqtx.html