單例模式(Singleton Pattern)是一種常用的軟件設(shè)計(jì)模式,該模式的主要目的是確保 某一個(gè)類只有一個(gè)實(shí)例存在 。當(dāng)希望在整個(gè)系統(tǒng)中,某個(gè)類只能出現(xiàn)一個(gè)實(shí)例時(shí),單例對(duì)象就能派上用場(chǎng)。
比如,某個(gè)服務(wù)器程序的配置信息存放在一個(gè)文件中,客戶端通過(guò)一個(gè) AppConfig 的類來(lái)讀取配置文件的信息。如果在程序運(yùn)行期間,有很多地方都需要使用配置文件的內(nèi)容,也就是說(shuō),很多地方都需要?jiǎng)?chuàng)建 AppConfig 對(duì)象的實(shí)例,這就導(dǎo)致系統(tǒng)中存在多個(gè) AppConfig 的實(shí)例對(duì)象,而這樣會(huì)嚴(yán)重浪費(fèi)內(nèi)存資源,尤其是在配置文件內(nèi)容很多的情況下。事實(shí)上,類似 AppConfig 這樣的類,我們希望在程序運(yùn)行期間只存在一個(gè)實(shí)例對(duì)象
python實(shí)現(xiàn)單例模式
使用模塊實(shí)現(xiàn)
Python 的模塊就是天然的單例模式 ,因?yàn)槟K在第一次導(dǎo)入時(shí),會(huì)生成 .pyc 文件,當(dāng)?shù)诙螌?dǎo)入時(shí),就會(huì)直接加載 .pyc 文件,而不會(huì)再次執(zhí)行模塊代碼。因此,我們只需把相關(guān)的函數(shù)和數(shù)據(jù)定義在一個(gè)模塊中,就可以獲得一個(gè)單例對(duì)象了。
mysingleton.py
1
2
3
4
|
class Singleton: def foo( self ): print ( 'foo' ) singleton = Singleton() |
其他文件
1
2
|
from mysingleton import singleton singleton.foo() |
裝飾器實(shí)現(xiàn)
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 ) |
最終實(shí)例化出一個(gè)對(duì)象并且保存在_instance中,_instance的值也一定是
基于__new__方法實(shí)現(xiàn)
當(dāng)我們實(shí)例化一個(gè)對(duì)象時(shí),是 先執(zhí)行了類的__new__方法 (我們沒寫時(shí),默認(rèn)調(diào)用object.__new__), 實(shí)例化對(duì)象 ;然后 再執(zhí)行類的__init__方法 ,對(duì)這個(gè)對(duì)象進(jìn)行初始化,所有我們可以基于這個(gè),實(shí)現(xiàn)單例模式
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) |
為了保證線程安全需要在內(nèi)部加入鎖
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. 除了模塊單例外,其他幾種模式的本質(zhì)都是通過(guò)設(shè)置中間變量,來(lái)判斷類是否已經(jīng)被實(shí)例。中間變量的訪問(wèn)和更改存在線程安全的問(wèn)題:在開啟多線程模式的時(shí)候需要加鎖處理。
2. __new__方法無(wú)法避免觸發(fā)__init__(),初始的成員變量會(huì)進(jìn)行覆蓋。 其他方法不會(huì)。
PS:下面看下Python單例模式的4種實(shí)現(xiàn)方法
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,實(shí)現(xiàn)__new__方法 #并在將一個(gè)類的實(shí)例綁定到類變量_instance上, #如果cls._instance為None說(shuō)明該類還沒有實(shí)例化過(guò),實(shí)例化該類,并返回 #如果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檢測(cè) print id (one) #29097904 print id (two) #29097904 print one = = two #True print one is two #True print '----------------------方法2--------------------------' #方法2,共享屬性;所謂單例就是所有引用(實(shí)例、對(duì)象)擁有相同的狀態(tài)(屬性)和行為(方法) #同一個(gè)類的所有實(shí)例天然擁有相同的行為(方法), #只需要保證同一個(gè)類的所有實(shí)例具有相同的狀態(tài)(屬性)即可 #所有實(shí)例共享屬性的最簡(jiǎn)單最直接的方法就是__dict__屬性指向(引用)同一個(gè)字典(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是兩個(gè)不同的對(duì)象,id, ==, is對(duì)比結(jié)果可看出 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具有相同的(同一個(gè)__dict__屬性),見: print id (one.__dict__) #30104000 print id (two.__dict__) #30104000 print '----------------------方法3--------------------------' #方法3:本質(zhì)上是方法1的升級(jí)(或者說(shuō)高級(jí))版 #使用__metaclass__(元類)的高級(jí)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的升級(jí)(高級(jí))版本, #使用裝飾器(decorator), #這是一種更pythonic,更elegant的方法, #單例類本身根本不知道自己是單例的,因?yàn)樗旧?自己的代碼)并不是單例的 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 |
總結(jié)
以上所述是小編給大家介紹的python實(shí)現(xiàn)單例模式方式詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://www.cnblogs.com/hantaozi430/p/8605275.html