美文网首页
python 增强的单例模式

python 增强的单例模式

作者: 圣_狒司机 | 来源:发表于2023-03-23 23:58 被阅读0次

一、 简单的单例模式

class Singleton:
 __instance = None
 
def __new__(cls):
    if cls.__instance is None:
        cls.__instance = super().__new__(cls)
        return cls.__instance

在不同的包里引用这个类,永远生成同一个实例,这个类也只有这一个实例。

二、 增强的单例模式

class Meta:
    _instances = {}
    def __new__(cls,*args):
        if args[0] in cls._instances:
            return cls._instances[args[0]]
        return super().__new__(cls)
    
    def __init__(self,name,left=None,right=None):
        self.name = name
        self.left = left
        self.right = right
        self._instances[name] = self

    @staticmethod
    def get(s):
        if s not in Meta._instances:
            return Meta(s)
        else:
            return Meta._instances[s]

测试一下:

import pytest
@pytest.fixture(scope="module")
def newclass():
    return Meta

def test_Meta(newclass):
    a = newclass("a")
    b = newclass.get("a")
    assert a == b

def test_Meta_count(newclass):
    c = newclass.get("c")
    assert newclass._instances.__len__() == 2

pytest.main()

2 passed in 0.45s

用类的实例化方法和get方法做了三个实例,因为有两个名字相同,所以只会生成两个实例。无论什么时候只要实例的名字一致,生成的实例都指向同一个,这样实现了用名字进行索引。

相关文章

  • 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单例模式实现方式 使用模板 python模块是天然的单例模式(.pyc文件的存在) 使用__new__...

  • 基础-单例模式

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

  • Python设计模式 之 Borg模式

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

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

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

  • Python经典面试题21道

    1、Python如何实现单例模式? Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模...

网友评论

      本文标题:python 增强的单例模式

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