github地址:https://github.com/cheesezh/python_design_patternshtml
單例模式(Singleton Pattern)是一種經常使用的軟件設計模式,該模式的主要目的是確保某一個類只有一個實例存在
。當你但願在整個系統中,某個類只能出現一個實例時,單例模式就能派上用場。python
好比,某個服務器程序的配置信息存放在一個文件中,客戶端經過一個 AppConfig 的類來讀取配置文件的信息。若是在程序運行期間,有不少地方都須要使用配置文件的內容,也就是說,不少地方都須要建立 AppConfig 對象的實例,這就致使系統中存在多個 AppConfig 的實例對象,而這樣會嚴重浪費內存資源,尤爲是在配置文件內容不少的狀況下。事實上,相似 AppConfig 這樣的類,咱們但願在程序運行期間只存在一個實例對象。git
在 Python 中,咱們能夠用多種方法來實現單例模式。github
其實,Python 的模塊就是自然的單例模式,由於模塊在第一次導入時,會生成 .pyc 文件,當第二次導入時,就會直接加載 .pyc 文件,而不會再次執行模塊代碼。所以,咱們只需把相關的函數和數據定義在一個模塊中,就能夠得到一個單例對象了。若是咱們真的想要一個單例類,能夠考慮這樣作:設計模式
# mysingleton.py class Singleton(object): def foo(self): pass singleton = Singleton()
將上面的代碼保存在文件 mysingleton.py 中,要使用時,直接在其餘文件中導入此文件中的對象,這個對象便是單例模式的對象安全
from a import singleton
def Singleton(cls): _instance = {} def _singleton(*args, **kargs): if cls not in _instance: _instance[cls] = cls(*args, **kargs) return _instance[cls] return _singleton @Singleton class A(object): a = 1 def __init__(self, x=0): self.x = x a1 = A(2) a2 = A(3) print(a1) print(a2)
<__main__.A object at 0x103496668> <__main__.A object at 0x103496668>
class Singleton(object): def __init__(self): pass @classmethod def instance(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): Singleton._instance = Singleton(*args, **kwargs) return Singleton._instance
通常狀況,你們覺得這樣就完成了單例模式,可是這樣當使用多線程時會存在問題
。服務器
class Singleton(object): def __init__(self): pass @classmethod def instance(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): Singleton._instance = Singleton(*args, **kwargs) return Singleton._instance import threading def task(arg): obj = Singleton.instance() print(obj) for i in range(10): t = threading.Thread(target=task,args=[i,]) t.start()
<__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8> <__main__.Singleton object at 0x1033e84a8>
看起來也沒有問題,那是由於執行速度過快,若是在init方法中有一些IO操做,就會發現問題了,下面咱們經過time.sleep模擬多線程
class Singleton(object): def __init__(self): import time time.sleep(0.5) pass @classmethod def instance(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): Singleton._instance = Singleton(*args, **kwargs) return Singleton._instance import threading def task(arg): obj = Singleton.instance() print(obj) for i in range(10): t = threading.Thread(target=task,args=[i,]) t.start()
<__main__.Singleton object at 0x1033b79e8> <__main__.Singleton object at 0x1033b7e10> <__main__.Singleton object at 0x103401ef0> <__main__.Singleton object at 0x103401c18> <__main__.Singleton object at 0x103401048> <__main__.Singleton object at 0x103401dd8> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401eb8> <__main__.Singleton object at 0x103401a58> <__main__.Singleton object at 0x103401fd0>
問題出現了!按照以上方式建立的單例,沒法支持多線程。併發
解決辦法:加鎖!未加鎖部分併發執行,加鎖部分串行執行,速度下降,可是保證了數據安全函數
import time import threading class Singleton(object): _instance_lock = threading.Lock() def __init__(self): time.sleep(0.5) @classmethod def instance(cls, *args, **kwargs): with Singleton._instance_lock: if not hasattr(Singleton, "_instance"): Singleton._instance = Singleton(*args, **kwargs) return Singleton._instance def task(arg): obj = Singleton.instance() print(obj) for i in range(10): t = threading.Thread(target=task,args=[i,]) t.start() time.sleep(5) obj = Singleton.instance() print(obj)
<__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00> <__main__.Singleton object at 0x103401b00>
這樣就差很少了,可是仍是有一點小問題,就是當程序執行時,執行了time.sleep(5)後,下面實例化對象時,此時已是單例模式了,但咱們仍是加了鎖,這樣不太好,再進行一些優化,須要修改一下intance方法。
import time import threading class Singleton(object): _instance_lock = threading.Lock() def __init__(self): time.sleep(0.5) @classmethod def instance(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): with Singleton._instance_lock: if not hasattr(Singleton, "_instance"): Singleton._instance = Singleton(*args, **kwargs) return Singleton._instance def task(arg): obj = Singleton.instance() print(obj) for i in range(10): t = threading.Thread(target=task,args=[i,]) t.start() time.sleep(5) obj = Singleton.instance() print(obj)
<__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550> <__main__.Singleton object at 0x1033db550>
這種方式實現的單例模式,使用時會有限制,之後實例化必須經過obj = Singleton.instance()
,若是用obj=Singleton()
,這種方式獲得的不是單例。
經過上面例子,咱們能夠知道,當咱們實現單例時,爲了保證線程安全須要在內部加入鎖。
咱們知道,當咱們實例化一個對象時,是先執行了類的__new__方法(咱們沒寫時,默認調用object.__new__)實例化對象;而後再執行類的__init__方法,對這個對象進行初始化,全部咱們能夠基於這個機制,實現單例模式。
import threading import time class Singleton(object): _instance_lock = threading.Lock() def __init__(self): time.sleep(0.5) def __new__(cls, *args, **kwargs): if not hasattr(Singleton, "_instance"): with Singleton._instance_lock: if not hasattr(Singleton, "_instance"): Singleton._instance = object.__new__(cls) return Singleton._instance obj1 = Singleton() obj2 = Singleton() print(obj1,obj2) def task(arg): obj = Singleton() print(obj) for i in range(10): t = threading.Thread(target=task,args=[i,]) t.start()
<__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70> <__main__.Singleton object at 0x103483b70>
採用這種方式的單例模式,之後實例化對象時,和平時實例化對象的方法同樣obj = Singleton()
class Foo: def __init__(self): print("Foo __init__") def __call__(self, *args, **kwargs): print("Foo __call__") # 執行type的 __call__ 方法 # 調用 Foo類(是type的對象)的 __new__方法,用於建立對象 # 而後調用 Foo類(是type的對象)的 __init__方法,用於對對象初始化。 obj = Foo() # 執行Foo的 __call__ 方法 obj()
Foo __init__ Foo __call__
class SingletonType(type): def __init__(self,*args,**kwargs): super(SingletonType,self).__init__(*args,**kwargs) def __call__(cls, *args, **kwargs): # 這裏的cls,即Foo類 print('cls',cls) obj = cls.__new__(cls,*args, **kwargs) cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj) return obj class Foo(metaclass=SingletonType): # 指定建立Foo的type爲SingletonType def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): return object.__new__(cls) obj = Foo('xx')
cls <class '__main__.Foo'>
import threading class SingletonType(type): _instance_lock = threading.Lock() def __call__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): with SingletonType._instance_lock: if not hasattr(cls, "_instance"): cls._instance = super(SingletonType,cls).__call__(*args, **kwargs) return cls._instance class Foo(metaclass=SingletonType): def __init__(self,name): self.name = name obj1 = Foo('name') obj2 = Foo('name') print(obj1) print(obj2)
<__main__.Foo object at 0x10348d908> <__main__.Foo object at 0x10348d908>
參考文章: Python中的單例模式的幾種實現方式的及優化