Five implementations of python singleton mode

__new__Special method implementation

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

tips: The new__method cannot avoid triggering __init(), the initial member variables will be overwritten

Decorator implementation

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''

def singleton(cls):
    _instance = {
    
    }
    def inner(*args, **kwargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)
        return _instance[cls]
    return inner

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

t1 = Test('first')
t2 = Test('last')
print(t1==t2)
>> True
print(t2.name)
>> first

Class decorator implementation

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 Cls2:
    def __init__(self, name):
        self.name = name

cls1 = Cls2('first')
cls2 = Cls2('last')
print(id(cls1) == id(cls2))
>> True
print(cls1.name)
>> first

Metaclass implementation

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class Singleton1(type):
    def __init__(self, *args, **kwargs):
        self.__instance = None
        super(Singleton1, self).__init__(*args, **kwargs)

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

class C(metaclass=Singleton1):
    def __init__(self, name):
        self.name = name

c1 = C('first')
c2 = C('last')
print(c1 == c2)
>> True
print(c2.name)
>> first

Module implementation

The Python module is a natural singleton mode, because the module will generate a .pyc file when it is imported for the first time. When it is imported for the second time, the .pyc file will be loaded directly without executing the module code again.

#foo1.py
class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()

#foo.py
from foo1 import singleton

Guess you like

Origin blog.csdn.net/qdPython/article/details/112988239