1. 程式人生 > 其它 >單例模式及實現單例模式的方法

單例模式及實現單例模式的方法

目錄

單例模式及實現單例模式的方法

一 單例模式

	"單例模式(Singleton Pattern)"是一種常用的軟體設計模式,該模式的主要目的是確保"某一個類只有一個例項存在"。當你希望在整個系統中,某個類只能出現一個例項時,單例物件就能派上用場。

	比如,某個伺服器程式的配置資訊存放在一個檔案中,客戶端通過一個 AppConfig 的類來讀取配置檔案的資訊。如果在程式執行期間,有很多地方都需要使用配置檔案的內容,也就是說,很多地方都需要建立 AppConfig 物件的例項,這就導致系統中存在多個 AppConfig 的例項物件,而這樣會嚴重浪費記憶體資源,尤其是在配置檔案內容很多的情況下。事實上,類似 AppConfig 這樣的類,我們希望在程式執行期間只存在一個例項物件。

二 實現單例模式的幾種方式

1 使用模組

	其實,"Python 的模組就是天然的單例模式",因為模組在第一次匯入時,會生成 `.pyc` 檔案,當第二次匯入時,就會直接載入 `.pyc` 檔案,而不會再次執行模組程式碼。因此,我們只需把相關的函式和資料定義在一個模組中,就可以獲得一個單例物件了。如果我們真的想要一個單例類,可以考慮這樣做:

mysingleton.py

# mysingleton.py

class Singleton(object):
    def foo(self):
        pass
singleton = Singleton()
	將上面的程式碼儲存在檔案 `mysingleton.py` 中,要使用時,直接在其他檔案中匯入此檔案中的物件,這個物件即是單例模式的物件
from a import singleton

2 使用裝飾器

def Singleton(cls):
    instance = None

    def _singleton(*args, "kargs):
        nonlocal instance
        if not instance:
            instance = cls(*args, "kargs)
        return instance

    return _singleton


@Singleton
class A(object):
    def __init__(self, x=0):
        self.x = x


a1 = A(2)
a2 = A(3)
print(a1.x)
print(a2.x)

print(a1 is a2)

3 使用類方法

class Singleton(object):
    _instance=None
    def __init__(self):
        pass
    @classmethod
    def instance(cls, *args, "kwargs):
        if not cls._instance:
            cls._instance=cls(*args, "kwargs)
        return cls._instance

a1=Singleton.instance()
a2=Singleton().instance()

print(a1 is a2)

4 基於__new__方法實現

class Singleton(object):
    _instance=None
    def __init__(self):
        pass


    def __new__(cls, *args, "kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls)
        return cls._instance

obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)

5 基於metaclass方式實現

class SingletonType(type):    _instance=None    def __call__(cls, *args, "kwargs):        if not cls._instance:            # cls._instance = super().__call__(*args, "kwargs)            cls._instance = object.__new__(cls)            cls._instance.__init__(*args, "kwargs)        return cls._instanceclass Foo(metaclass=SingletonType):    def __init__(self,name):        self.name = nameobj1 = Foo('name')obj2 = Foo('name')print(obj1.name)print(obj1 is obj2)