Python实现单例模式

2020-03-23  本文已影响0人  Yimmy_Lee

1.使用__new__实现

# 方法1
class Singleton(object):
    _singleton = {}

    def __new__(cls):
        if not cls._singleton.keys():  # 若还没有任何实例
            cls._singleton[cls] = object.__new__(cls)  # 创建一个实例
        return cls._singleton[cls]


a = Singleton()
print(id(a))
b = Singleton()
print(id(b))
# out
# 1751876996288
# 1751876996288

# 方法2
class Singleton:

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

    def __init__(self, name):
        self.name = name

s1 = Singleton('first')
s2= Singleton('last')
print(s1 == s2)
>> True
print(s1.name)
>> last

2.使用装饰器实现单例

# 装饰器实现单例
def singleton(cls):  # cls 是一个函数
    _instance = {}

    def inner(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]
    return inner  # inner 返回的也是一个函数


@singleton
class Singleton2:
    def __init__(self, name):
        self.name = name


ss1 = Singleton2("Jack")
ss2 = Singleton2("Tom")
print(ss2.name)  # Jack

3.类装饰器实现单例

class SingleTon:
    def __init__(self, cls):
        self._cls = cls
        self._instance = {}

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


@SingleTon
class People:
    def __init__(self, name):
        self.name = name


p1 = People("Lucy")
p2 = People("Rose")
print(p1 == p2)
print(p2.name)

# True
# Lucy

4.元类实现

class Singleton2(type):
    def __init__(self, *args, **kwargs):
        self.__instance = None
        super(Singleton2, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super(Singleton2, self).__call__(*args, **kwargs)
        return self.__instance

class Test(metaclass=Singleton2):
    def __init__(self, name):
        self.name = name

T1 = Test('first')
T2 = Test('last')
print(T1 == T2)
>> True
print(T2.name)
>> first
上一篇下一篇

猜你喜欢

热点阅读