欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python設(shè)計模式之單例模式你了解多少

 更新時間:2022年03月04日 10:55:30   作者:托塔天王李  
這篇文章主要為大家詳細介紹了python設(shè)計模式之單例模式,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助

單例模式

概念

單例模式:“保證一個類僅有一個實例,并提供一個訪問它的在這里插入代碼片全局訪問點。
單例模式會阻止其他對象實例化其自己的單例對象的副本,從而確保所有對象都訪問唯一實例。
單例模式應(yīng)用的場景一般發(fā)現(xiàn)在以下條件下:
(1)資源共享的情況下,避免由于資源操作時導(dǎo)致的性能或損耗等。如上述中的日志文件,應(yīng)用配置。
(2)控制資源的情況下,方便資源之間的互相通信。如線程池等。

單例模式使用場景

 - Web應(yīng)用的配置對象的讀取
 - Windows的Task Manager(任務(wù)管理器)
 - 網(wǎng)站的計數(shù)器,一般也是采用單例模式實現(xiàn),否則難以同步
 - 應(yīng)用程序的日志應(yīng)用,一般都何用單例模式實現(xiàn),這一般是由于共享的日志文件一直處于打開狀態(tài),因為只能有一個實例去操作,否則內(nèi)容不好追加
 - 數(shù)據(jù)庫連接池的設(shè)計一般也是采用單例模式,因為數(shù)據(jù)庫連接是一種數(shù)據(jù)庫資源
 - 多線程的線程池的設(shè)計一般也是采用單例模式,這是由于線程池要方便對池中的線程進行控制。
 - 

python實現(xiàn)單例模式 

函數(shù)裝飾器實現(xiàn)單例

def singleton(class_):
	instances = {)
	def get_instance(*args, **kwargs):
		if class_ not in instances:
			instances[class_] = class_(*argx, **kwargs)
		return instances[class_]
	reyurn get_instance
@singleton
class Cls(object):
    def __init__(self):
        pass
cls1 = Cls()
cls2 = Cls()
print(id(cls1) == id(cls2))

輸出結(jié)果:

True

instances = {)

使用不可變的類地址作為鍵,其實例作為值,每次創(chuàng)造實例時,首先查看該類是否存在實例,存在的話直接返回該實例即可,否則新建一個實例并存放在字典中。

使用模塊 (常用)實現(xiàn)單例

作為python的模塊是天然的單例模式

# mysingleton.py
class My_Singleton(object):
    def foo(self):
        pass
my_singleton = My_Singleton()
# to use
from mysingleton import my_singleton
my_singleton.foo()

基于__new__實現(xiàn)的單例模式(最常用)

類(class)通過方法 new 創(chuàng)造了實例(instance)

class Single(object):
    _instance = None
    def __new__(cls, *args, **kw):
        if cls._instance is None:
            orig = super(Single, cls)
            cls._instance = orig.__new__(cls, *args, **kw)
        return cls._instance
    def __init__(self):
        pass
single1 = Single()
single2 = Single()
print(id(single1) == id(single2))

如果 _instance 為 None,則新建實例,否則直接返回 _instance 存放的實例。

使用 metaclass 實現(xiàn)單例模式

元類(metaclass) 可以通過方法 metaclass 創(chuàng)造了類(class)

class Singleton(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]
class Cls4(metaclass=Singleton):
    pass
cls1 = Cls4()
cls2 = Cls4()
print(id(cls1) == id(cls2))

我們將 metaclass 指向 Singleton 類,讓 Singleton 中的 type 來創(chuàng)造新的 Cls4 實例

web應(yīng)用配置文件單例實現(xiàn)

def singleton(class_):
    instances = {}
    def getinstance(*args, **kwargs):
        if class_ not in instances:
            instances[class_] = class_(*args, **kwargs)
        return instances[class_]
    return getinstance
@singleton
class Config(dict):
    """
    配置文件類  單例模式
    """
    def __init__(self):
        self.__can_import = True
        self.__init_default()
        dict.__init__(self)
    def __init_default(self):
        self['debug'] = False
        self['autoreload'] = True
    @property
    def can_import(self):
        return self.__can_import
    def import_dict(self, **kwargs):
        if self.__can_import:
            for k, v in kwargs.items():
                self[k] = v
            self.__can_import = False
        else:
            raise Exception('ConfigImportError')
    def clear(self):
        self.__can_import = True
        dict.clear(self)
        self.__init_default()

總結(jié)

本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!      

相關(guān)文章

最新評論