1. 程式人生 > >Python-設計模式:單例模式

Python-設計模式:單例模式

1. 單例是什麼

舉個常見的單例模式例子,我們日常使用的電腦上都有一個回收站,在整個作業系統中,回收站只能有一個例項,整個系統都使用這個唯一的例項,而且回收站自行提供自己的例項。因此回收站是單例模式的應用。

確保某一個類只有一個例項,而且自行例項化並向整個系統提供這個例項,這個類稱為單例類,單例模式是一種物件建立型模式。

2. 建立單例-保證只有1個物件


# 例項化一個單例
class Singleton(object):
    __instance = None

    def __new__(cls, age, name):
        #如果類屬性__instance的值為None,
        #那麼就建立一個物件,並且賦值為這個物件的引用,保證下次呼叫這個方法時
        #能夠知道之前已經建立過物件了,這樣就保證了只有1個物件
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

a = Singleton(18, "dongGe")
b = Singleton(8, "dongGe")

print(id(a))
print(id(b))

a.age = 19 #給a指向的物件新增一個屬性
print(b.age)#獲取b指向的物件的age屬性

執行結果:

In [12]: class Singleton(object):
    ...:     __instance = None
    ...: 
    ...:     def __new__(cls, age, name):
    ...:         if not cls.__instance:
    ...:             cls.__instance = object.__new__(cls)
    ...:         return cls.__instance
    ...: 
    ...: a = Singleton(18, "dongGe")
    ...: b = Singleton(8, "dongGe")
    ...: 
    ...: print(id(a))
    ...: print(id(b))
    ...: 
    ...: a.age = 19
    ...: print(b.age)
    ...: 
4391023224
4391023224
19

3. 建立單例時,只執行1次__init__方法


# 例項化一個單例
class Singleton(object):
    __instance = None
    __is_first = True

    def __new__(cls, age, name):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __init__(self, age, name):
        if self. __is_first:
            self.age = age
            self.name = name
            Singleton. __is_first = False


a = Singleton(18, "習大大")
b = Singleton(28, "習大大")

print(id(a))
print(id(b))


print(a.age)
print(b.age)

a.age = 19
print(b.age)

執行結果: