__new__
特殊方法實現
class
singleton
:def
__new__
(cls,
*args,
**kwargs):if
nothasattr
(cls,
'_instance'):
cls._instance =
super
(singleton, cls)
.__new__(cls)
return cls._instance
def__init__
(self, name)
: self.name = name
s1 = singleton(
'first'
)s2= singleton(
'last'
)print
(s1 == s2)
>>
true
print
(s1.name)
>> last
tips:new__
方法無法避免觸發__init()
,初始的成員變數會進行覆蓋
裝飾器實現
'''
'''def
singleton
(cls)
: _instance =
definner
(*args,
**kwargs)
:if cls not
in _instance:
_instance[cls]
= cls(
*args,
**kwargs)
return _instance[cls]
return inner
@singleton
class
test
:def
__init__
(self, name)
: self.name = name
t1 = test(
'first'
)t2 = test(
'last'
)print
(t1==t2)
>>
true
print
(t2.name)
>> first
類裝飾器實現
class
singleton
:def
__init__
(self, cls)
: self._cls = cls
self._instance =
def__call__
(self,
*args)
:if self._cls not
in self._instance:
self._instance[self._cls]
= self._cls(
*args)
return self._instance[self._cls]
@singleton
class
cls2
:def
__init__
(self, name)
: self.name = name
cls1 = cls2(
'first'
)cls2 = cls2(
'last'
)print(id
(cls1)
==id
(cls2)
)>>
true
print
(cls1.name)
>> first
元類實現
'''
'''class
singleton1
(type):
def__init__
(self,
*args,
**kwargs)
: self.__instance =
none
super
(singleton1, self)
.__init__(
*args,
**kwargs)
def__call__
(self,
*args,
**kwargs)
:if self.__instance is
none
: self.__instance =
super
(singleton1, self)
.__call__(
*args,
**kwargs)
return self.__instance
class
c(metaclass=singleton1)
:def
__init__
(self, name)
: self.name = name
c1 = c(
'first'
)c2 = c(
'last'
)print
(c1 == c2)
>>
true
print
(c2.name)
>> first
模組實現
python 的模組就是天然的單例模式,因為模組在第一次匯入時,會生成 .pyc 檔案,當第二次匯入時,就會直接載入 .pyc 檔案,而不會再次執行模組**。
#foo1.py
class
singleton
(object):
deffoo
(self)
:pass
singleton = singleton(
)#foo.py
from foo1 import singleton
五種單例模式實現
public class hunger private final static hunger hunger newhunger public static hunger getinstance 多個執行緒安全,但無法進行懶載入,如果類成員很多,則占用的資源比較多 public class lazy...
單例模式的五種實現
1.1懶漢式,執行緒不安全 單例模式在多執行緒的 應用場合下必須小心使用。如果當唯一例項尚未建立時,有兩個執行緒同時呼叫建立方法,那麼它們同時沒有檢測到唯一例項的存在,從 而同時各自建立了乙個例項,這樣就有兩個例項被構造出來,從而違反了單例模式中例項唯一的原則。解決這個問題的辦法是為指示類是否已經例...
Python 單例模式實現的五種方式
全域性變數 ip 192.168.13.98 port 3306 class mysql instance none def init self,ip,port self.ip ip self.port port classmethod def instance cls,args,kwargs if...