Python實現單例模式

單例模式

1.什麼是單例?

確保某一個類只有一個實例,並且自行實例化並向整個系統提供這個實例,這個類稱爲單例類,單例模式是一種對象建立型模式。
那麼單例模式有什麼用途呢?舉個常見的單例模式例子,咱們平時使用的電腦上都有一個回收站,在整個操做系統中,回收站只能有一個實例,整個系統都使用這個惟一的實例,並且回收站自行提供本身的實例,所以回收站是單例模式的應用。ide

2.建立單例-保證只有1個對象

class Singleton(object):
    __instance = None

    def __new__(cls, name, age):
        # 若是類屬性__instance的值爲None,那麼就建立一個對象
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        # 若是已經有實例存在,直接返回
        return cls.__instance

a = Singleton("Zhangsan", 18)
b = Singleton("lisi", 20)

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

a.age = 30   # 給a指向的對象添加一個屬性
print(b.age)  # 獲取b指向的對象的age屬性

運行結果:操作系統

2946414454432
2946414454432
30

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

class Singleton(object):
    __instance = None
    __first_init = False

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

    def __init__(self, name, age):
        if not self.__first_init:
            self.name = name
            self.age = age
            Singleton.__first_init = True

a = Singleton("Zhangsan", 18)
b = Singleton("lisi", 20)

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

print(a.name, a.age)
print(b.name, b.age)

a.age = 50
print(b.age)

運行結果:code

2206640285344
2206640285344
Zhangsan 18
Zhangsan 18
50
相關文章
相關標籤/搜索