python---实现单例模式

"""
单例模式

单利模式是一种设计模式, 应用该模式的类只会生成一个实例, 可以保证在程序的不同位置
都可以且仅可以取到同一个对象实例.

如果实例不存在, 会创建一个实例, 但是如果已经存在就会返回这个实例.

四种实现方法:
1.函数装饰器实现单例模式
2.类装饰器实现单例模式
3.__new__实现单例模式
4.metaclass实现单利模式
"""


# 1.函数装饰器实现单例模式

def singleton(cls):
    _instance = {}

    def get_instance():
        # 实例不存在创建实例
        if cls not in _instance:
            _instance[cls] = cls()

        # 实例存在直接返回
        return _instance[cls]

    return get_instance


@singleton
class Cls(object):
    def __init__(self):
        pass


cls1 = Cls()
cls2 = Cls()
print(id(cls1) == id(cls2))  # True


# 2.类装饰器实现单例模式

class Singleton(object):
    def __init__(self, cls):
        self.cls = cls
        self._instance = {}

    def __call__(self):
        if self.cls not in self._instance:
            self._instance[self.cls] = self.cls()

        return self._instance[self.cls]


@Singleton
class Cls2(object):
    def __init__(self):
        pass


cls3 = Cls2()
cls4 = Cls2()
print(id(cls3) == id(cls4))  # True


# 3.__new__实现单例模式, 在创建实例的时候进行干预

class Singleton2(object):
    _instance = None

    def __new__(cls, *args, **kwargs):

        # 实例不存在创建实例
        if cls._instance is None:
            cls._instance = super().__new__(cls, *args, **kwargs)

        # 实例存在直接返回
        return cls._instance

    def __init__(self):
        pass


single1 = Singleton2()
single2 = Singleton2()
print(single1 == single2)  # True


# 4.metaclass实现单利模式, 元类metaclass可以通过方法__metaclass__创造类

class Singleton3(type):
    _instance = {}

    def __call__(cls, *args, **kwargs):

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

        return cls._instance[cls]


class Cls3(metaclass=Singleton3):
    pass


cls5 = Cls3()
cls6 = Cls3()
print(id(cls5) == id(cls6))  # True

posted @ 2020-04-04 17:35  凯旋.Lau  阅读(159)  评论(0编辑  收藏  举报