日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python实现单例模式的几种方式_基于Python中单例模式的几种实现方式及优化详解...

發布時間:2023/12/1 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python实现单例模式的几种方式_基于Python中单例模式的几种实现方式及优化详解... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

單例模式

單例模式(Singleton Pattern)是一種常用的軟件設計模式,該模式的主要目的是確保某一個類只有一個實例存在。當你希望在整個系統中,某個類只能出現一個實例時,單例對象就能派上用場。

比如,某個服務器程序的配置信息存放在一個文件中,客戶端通過一個 AppConfig 的類來讀取配置文件的信息。如果在程序運行期間,有很多地方都需要使用配置文件的內容,也就是說,很多地方都需要創建 AppConfig 對象的實例,這就導致系統中存在多個 AppConfig 的實例對象,而這樣會嚴重浪費內存資源,尤其是在配置文件內容很多的情況下。事實上,類似 AppConfig 這樣的類,我們希望在程序運行期間只存在一個實例對象。

在 Python 中,我們可以用多種方法來實現單例模式

實現單例模式的幾種方式

1.使用模塊

其實,Python 的模塊就是天然的單例模式,因為模塊在第一次導入時,會生成 .pyc 文件,當第二次導入時,就會直接加載 .pyc 文件,而不會再次執行模塊代碼。因此,我們只需把相關的函數和數據定義在一個模塊中,就可以獲得一個單例對象了。如果我們真的想要一個單例類,可以考慮這樣做:

mysingleton.py

class Singleton(object):

def foo(self):

pass

singleton = Singleton()

將上面的代碼保存在文件 mysingleton.py 中,要使用時,直接在其他文件中導入此文件中的對象,這個對象即是單例模式的對象

from a import singleton

2.使用類

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()

程序執行后,打印結果如下:

看起來也沒有問題,那是因為執行速度過快,如果在init方法中有一些IO操作,就會發現問題了,下面我們通過time.sleep模擬

我們在上面__init__方法中加入以下代碼:

def __init__(self): import time time.sleep(1)

重新執行程序后,結果如下

問題出現了!按照以上方式創建的單例,無法支持多線程

解決辦法:加鎖!未加鎖部分并發執行,加鎖部分串行執行,速度降低,但是保證了數據安全

import time

import threading

class Singleton(object):

_instance_lock = threading.Lock()

def __init__(self):

time.sleep(1)

@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(20)

obj = Singleton.instance()

print(obj)

打印結果如下:

這樣就差不多了,但是還是有一點小問題,就是當程序執行時,執行了time.sleep(20)后,下面實例化對象時,此時已經是單例模式了,但我們還是加了鎖,這樣不太好,再進行一些優化,把intance方法,改成下面的這樣就行:

@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

這樣,一個可以支持多線程的單例模式就完成了

import time

import threading

class Singleton(object):

_instance_lock = threading.Lock()

def __init__(self):

time.sleep(1)

@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(20)

obj = Singleton.instance()

print(obj)

這種方式實現的單例模式,使用時會有限制,以后實例化必須通過 obj = Singleton.instance()

如果用 obj=Singleton() ,這種方式得到的不是單例

3.基于__new__方法實現(推薦使用,方便)

通過上面例子,我們可以知道,當我們實現單例時,為了保證線程安全需要在內部加入鎖

我們知道,當我們實例化一個對象時,是先執行了類的__new__方法(我們沒寫時,默認調用object.__new__),實例化對象;然后再執行類的__init__方法,對這個對象進行初始化,所有我們可以基于這個,實現單例模式

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()

打印結果如下:

采用這種方式的單例模式,以后實例化對象時,和平時實例化對象的方法一樣 obj = Singleton()

4.基于metaclass方式實現

相關知識

"""

1.類由type創建,創建類時候type的__init__方法自動執行,類() 執行type的 __call__方法(類的__new__方法,類的__init__方法)

2.對象由類創建,創建對象時候類的__init__方法自動執行,對象()執行類的 __call__ 方法

"""

例子:

class Foo:

def __init__(self):

pass

def __call__(self, *args, **kwargs):

pass

obj = Foo()

# 執行type的 __call__ 方法,調用 Foo類(是type的對象)的 __new__方法,用于創建對象,然后調用 Foo類(是type的對象)的 __init__方法,用于對對象初始化。

obj() # 執行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):

pass

def __new__(cls, *args, **kwargs):

return object.__new__(cls, *args, **kwargs)

obj = 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,obj2)

以上這篇基于Python中單例模式的幾種實現方式及優化詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持我們。

本文標題: 基于Python中單例模式的幾種實現方式及優化詳解

本文地址: http://www.cppcns.com/jiaoben/python/217200.html

總結

以上是生活随笔為你收集整理的python实现单例模式的几种方式_基于Python中单例模式的几种实现方式及优化详解...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。