亲宝软件园·资讯

展开

Python 单例模式 Python实现单例模式的5种方法

云崖先生 人气:0
想了解Python实现单例模式的5种方法的相关内容吗,云崖先生在本文为您仔细讲解Python 单例模式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,单例模式,下面大家一起来学习吧。

基本介绍

一个对象只允许被一次创建,一个类只能创建一个对象,并且提供一个全局访问点。

单例模式应该是应用最广泛,实现最简单的一种创建型模式。

特点:全局唯一,允许更改

优缺点

优点:

缺点:

Python实现

方式1,元类实现:

class MetaClass(type):
    def __call__(self, *args, **kwargs):
        """
        self : class Singleton
        """
        if not hasattr(self, "ins"):
            insObject = super(__class__, self).__call__(*args, **kwargs)
            setattr(self, "ins", insObject)
        return getattr(self, "ins")


class Singleton(object, metaclass=MetaClass):
    pass


if __name__ == "__main__":
    ins = Singleton()
    print(id(ins))
    ins = Singleton()
    print(id(ins))

方式2,继承实现:

class ParentClass:
    def __new__(cls, *args, **kwargs) -> object:
        """
        cls : class Singeton
        """
        if not hasattr(cls, "ins"):
            insObject = super(__class__, cls).__new__(cls, *args, **kwargs)
            setattr(cls, "ins", insObject)
        return getattr(cls, "ins")


class Singleton(ParentClass):
    pass


if __name__ == "__main__":
    ins = Singleton()
    print(id(ins))
    ins = Singleton()
    print(id(ins))

方式3,装饰器实现:

def warpper(clsObject):
    def inner(*args, **kwargs):
        if not hasattr(clsObject, "ins"):
            insObject = clsObject(*args, **kwargs)
            setattr(clsObject, "ins", insObject)
        return getattr(clsObject, "ins")
    return inner


@warpper
class Singleton:
    pass


if __name__ == "__main__":
    ins = Singleton()
    print(id(ins))
    ins = Singleton()
    print(id(ins))

方式4,模块实现:

- foo.py --> ins = Singleton()
- bar.py --> from foo import ins

方式5,@classmethod实现单例模式:

class Singleton:

    @classmethod
    def getSingletonInstanceObject(cls, *args, **kwargs):
        if not hasattr(cls, "ins"):
            insObject = cls(*args, **kwargs)
            setattr(cls, "ins", insObject)
        return getattr(cls, "ins")


if __name__ == "__main__":
    ins = Singleton.getSingletonInstanceObject()
    print(id(ins))
    ins = Singleton.getSingletonInstanceObject()
    print(id(ins))

加载全部内容

相关教程
猜你喜欢
用户评论