單例模式(Singleton Pattern)是一種常用的軟件設計模式,該模式的主要目的是確保 某一個類只有一個實例存在 。當希望在整個系統中,某個類只能出現一個實例時,單例對象就能派上用場。
比如,某個服務器程序的配置信息存放在一個文件中,客戶端通過一個 AppConfig 的類來讀取配置文件的信息。如果在程序運行期間,有很多地方都需要使用配置文件的內容,也就是說,很多地方都需要創建 AppConfig 對象的實例,這就導致系統中存在多個 AppConfig 的實例對象,而這樣會嚴重浪費內存資源,尤其是在配置文件內容很多的情況下。事實上,類似 AppConfig 這樣的類,我們希望在程序運行期間只存在一個實例對象
python實現單例模式
使用模塊實現
Python 的模塊就是天然的單例模式 ,因為模塊在第一次導入時,會生成 .pyc 文件,當第二次導入時,就會直接加載 .pyc 文件,而不會再次執行模塊代碼。因此,我們只需把相關的函數和數據定義在一個模塊中,就可以獲得一個單例對象了。
mysingleton.py
1
2
3
4
|
class Singleton: def foo( self ): print ( 'foo' ) singleton = Singleton() |
其他文件
1
2
|
from mysingleton import singleton singleton.foo() |
裝飾器實現
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def singleton( cls ): _instance = {} def wraper( * args, * * kargs): if cls not in _instance: _instance[ cls ] = cls ( * args, * * kargs) return _instance[ cls ] return wraper @singleton class A( object ): def __init__( self , x = 0 ): self .x = x a1 = A( 2 ) a2 = A( 3 ) |
最終實例化出一個對象并且保存在_instance中,_instance的值也一定是
基于__new__方法實現
當我們實例化一個對象時,是 先執行了類的__new__方法 (我們沒寫時,默認調用object.__new__), 實例化對象 ;然后 再執行類的__init__方法 ,對這個對象進行初始化,所有我們可以基于這個,實現單例模式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Singleton(): def __new__( cls , * args, * * kwargs): if not hasattr ( cls , '_instance' ): cls ._instance = object .__new__( cls ) return cls ._instance class A(Singleton): def __init__( self ,x): self .x = x a = A( 'han' ) b = A( 'tao' ) print (a.x) print (b.x) |
為了保證線程安全需要在內部加入鎖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import threading class Singleton(): lock = threading.Lock def __new__( cls , * args, * * kwargs): if not hasattr ( cls , '_instance' ): with cls .lock: if not hasattr ( cls , '_instance' ): cls ._instance = object .__new__( cls ) return cls ._instance class A(Singleton): def __init__( self ,x): self .x = x a = A( 'han' ) b = A( 'tao' ) print (a.x) print (b.x) |
兩大注意:
1. 除了模塊單例外,其他幾種模式的本質都是通過設置中間變量,來判斷類是否已經被實例。中間變量的訪問和更改存在線程安全的問題:在開啟多線程模式的時候需要加鎖處理。
2. __new__方法無法避免觸發__init__(),初始的成員變量會進行覆蓋。 其他方法不會。
PS:下面看下Python單例模式的4種實現方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
#-*- encoding=utf-8 -*- print '----------------------方法1--------------------------' #方法1,實現__new__方法 #并在將一個類的實例綁定到類變量_instance上, #如果cls._instance為None說明該類還沒有實例化過,實例化該類,并返回 #如果cls._instance不為None,直接返回cls._instance class Singleton( object ): def __new__( cls , * args, * * kw): if not hasattr ( cls , '_instance' ): orig = super (Singleton, cls ) cls ._instance = orig.__new__( cls , * args, * * kw) return cls ._instance class MyClass(Singleton): a = 1 one = MyClass() two = MyClass() two.a = 3 print one.a #3 #one和two完全相同,可以用id(), ==, is檢測 print id (one) #29097904 print id (two) #29097904 print one = = two #True print one is two #True print '----------------------方法2--------------------------' #方法2,共享屬性;所謂單例就是所有引用(實例、對象)擁有相同的狀態(屬性)和行為(方法) #同一個類的所有實例天然擁有相同的行為(方法), #只需要保證同一個類的所有實例具有相同的狀態(屬性)即可 #所有實例共享屬性的最簡單最直接的方法就是__dict__屬性指向(引用)同一個字典(dict) #可參看:http://code.activestate.com/recipes/66531/ class Borg( object ): _state = {} def __new__( cls , * args, * * kw): ob = super (Borg, cls ).__new__( cls , * args, * * kw) ob.__dict__ = cls ._state return ob class MyClass2(Borg): a = 1 one = MyClass2() two = MyClass2() #one和two是兩個不同的對象,id, ==, is對比結果可看出 two.a = 3 print one.a #3 print id (one) #28873680 print id (two) #28873712 print one = = two #False print one is two #False #但是one和two具有相同的(同一個__dict__屬性),見: print id (one.__dict__) #30104000 print id (two.__dict__) #30104000 print '----------------------方法3--------------------------' #方法3:本質上是方法1的升級(或者說高級)版 #使用__metaclass__(元類)的高級python用法 class Singleton2( type ): def __init__( cls , name, bases, dict ): super (Singleton2, cls ).__init__(name, bases, dict ) cls ._instance = None def __call__( cls , * args, * * kw): if cls ._instance is None : cls ._instance = super (Singleton2, cls ).__call__( * args, * * kw) return cls ._instance class MyClass3( object ): __metaclass__ = Singleton2 one = MyClass3() two = MyClass3() two.a = 3 print one.a #3 print id (one) #31495472 print id (two) #31495472 print one = = two #True print one is two #True print '----------------------方法4--------------------------' #方法4:也是方法1的升級(高級)版本, #使用裝飾器(decorator), #這是一種更pythonic,更elegant的方法, #單例類本身根本不知道自己是單例的,因為他本身(自己的代碼)并不是單例的 def singleton( cls , * args, * * kw): instances = {} def _singleton(): if cls not in instances: instances[ cls ] = cls ( * args, * * kw) return instances[ cls ] return _singleton @singleton class MyClass4( object ): a = 1 def __init__( self , x = 0 ): self .x = x one = MyClass4() two = MyClass4() two.a = 3 print one.a #3 print id (one) #29660784 print id (two) #29660784 print one = = two #True print one is two #True one.x = 1 print one.x #1 print two.x #1 |
總結
以上所述是小編給大家介紹的python實現單例模式方式詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/hantaozi430/p/8605275.html