1. 程式人生 > 其它 >Python中的單例模式

Python中的單例模式

單例模式(Singleton Pattern)是一種常用的軟體設計模式。主要目的是確保某一個類只有一個例項存在。
所以適用於類例項在__init__ 方法中不含有初始化引數的情況。

實現方式

__new__ 實現

class Single:
    _instance = {}

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

    def say(self, a, b):
        print(a + b)


c1 = Single()
c2 = Single()

print(id(c1))
print(id(c2))
print(c1 is c2)
print(c1.say(1, 2) is c2.say(1, 2))

函式裝飾器實現

def singleton_func(cls):
    _instance = {}

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

    return inner


@singleton_func
class Cls02:
    def say(self, a, b):
        print(a+b)


cls1 = Cls02()
cls2 = Cls02()
print(id(cls1) == id(cls2))
cls1.say(1, 2)

metaclass 實現

class SingletonCall(type):
    _instances = {}

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


class Cls4(metaclass=SingletonCall):

    def add(self, a, b):
        return a + b


p1 = Cls4()
p2 = Cls4()
print(id(p1) == id(p2))
print(p2.add(1, 2) is p1.add(1, 2))

類裝飾器實現

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

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


@SingletonCls
class Cls2(object):
    pass


cls1 = Cls2()
cls2 = Cls2()
print(id(cls1) == id(cls2))