Python中單例模式總結(jié)
一、單例模式
a、單例模式分為四種:文件,類,基于__new__方法實現(xiàn)單例模式,基于metaclass方式實現(xiàn)
b、類實現(xiàn)如下:
class Sigletion(objects):
import time
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls,*args,**kwargs)
if not hasattr(Sigletion,'_instance'):
Sigletion._instance=Sigletion(*args,**kwargs)
return Sigletion._instance
import threading
daf task(arg):
obj=Sigletion.instance()
print(obj)
for i in range(10):
t=threading.Thread(target=task,args=[i,])
t.start()
c、基于__new__方法實現(xiàn)單例模式
import time
import threading
class Singleton(object):
_instance_lock=threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(Singleton,"_instance"):
with Singleton._instance_lock:
if not hasattr(Singleton,"_instance"):
Singleton._instance=object.__new__(cls,*args,**kwargs)
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()
d、基于metaclass方式實現(xiàn)單例模式
"""
1.對象是類創(chuàng)建,創(chuàng)建對象時候類的__init__方法自動執(zhí)行,對象()執(zhí)行類的 __call__ 方法
2.類是type創(chuàng)建,創(chuàng)建類時候type的__init__方法自動執(zhí)行,類() 執(zhí)行type的 __call__方法(類的__new__方法,類的__init__方法)
# 第0步: 執(zhí)行type的 __init__ 方法【類是type的對象】
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
pass
# 第1步: 執(zhí)行type的 __call__ 方法
# 1.1 調(diào)用 Foo類(是type的對象)的 __new__方法,用于創(chuàng)建對象。
# 1.2 調(diào)用 Foo類(是type的對象)的 __init__方法,用于對對象初始化。
obj = Foo()
# 第2步:執(zhí)行Foodef __call__ 方法
obj()
"""
import threading
class SingletonType(type):
_instace_lock=threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with SingletonType._instace_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,obj2)
相關(guān)文章
Python函數(shù)默認參數(shù)設(shè)置的具體方法
本文主要介紹了Python函數(shù)默認參數(shù)設(shè)置,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Python中隨機休眠技術(shù)原理與應(yīng)用詳解
在編程中,讓程序暫停執(zhí)行特定時間是常見需求,當需要引入不確定性時,"隨機休眠"就成為關(guān)鍵技巧,下面我們就來看看Python中隨機休眠技術(shù)的具體實現(xiàn)與應(yīng)用吧2025-03-03
Python使用argcomplete模塊實現(xiàn)自動補全
argcomplete?是一個強大的Python庫,可以大幅改善命令行應(yīng)用程序的用戶體驗,本文主要介紹了argcomplete模塊的相關(guān)用法,感興趣的小伙伴可以了解下2023-11-11
在Apache服務(wù)器上同時運行多個Django程序的方法
這篇文章主要介紹了在Apache服務(wù)器上同時運行多個Django程序的方法,Django是Python各色高人氣web框架中最為著名的一個,需要的朋友可以參考下2015-07-07
基于np.arange與np.linspace細微區(qū)別(數(shù)據(jù)溢出問題)
這篇文章主要介紹了基于np.arange與np.linspace細微區(qū)別(數(shù)據(jù)溢出問題),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

