Python?設(shè)計模式創(chuàng)建型單例模式
一、單例模式
單例模式,實現(xiàn)一個類,并且保證這個類的多次實例化操作,都會只生成同一個實例對象。
二、應(yīng)用場景
整個系統(tǒng)中只需要存在一個實例對象,其他對象都可以通過訪問該對象來獲取信息,比如:
- 系統(tǒng)的配置信息對象
- 日志對象
- 數(shù)據(jù)庫操作對象
- 線程池對象
三、編碼示例
1.單線程中的單例模式
方式一、重載類構(gòu)造器
定義:
class Singleton(object): ? ? _instance = None ? ? def __new__(cls, *args, **kwargs): ? ? ? ? if cls._instance is None: ? ? ? ? ? ? cls._instance = object.__new__(cls, *args, **kwargs) ? ? ? ? return cls._instance
使用:
if __name__ == '__main__': ? ? instance1 = Singleton() ? ? instance2 = Singleton() ? ? instance3 = Singleton() ? ? # 打印出 3 個實例對象的內(nèi)存地址,判斷是否相同。 ? ? print(id(instance1)) ? ? print(id(instance2)) ? ? print(id(instance3))
方式二、實現(xiàn)單例裝飾器
定義:
def singleton(cls):
? ? _instance = {}
? ? def _singleton(*args, **kargs):
? ? ? ? if cls not in _instance:
? ? ? ? ? ? _instance[cls] = cls(*args, **kargs)
? ? ? ? return _instance[cls]
? ? return _singleton使用:
@singleton
class Singleton(object):
? ? """單例實例"""
? ? def __init__(self, arg1):
? ? ? ? self.arg1 = arg1
if __name__ == '__main__':
? ? instance1 = Singleton("xag")
? ? instance2 = Singleton("xingag")
? ? print(id(instance1))
? ? print(id(instance2))2.多線程中的單例模式
方式三、重載具有線程鎖的類構(gòu)造器
多線程中的單例模式,需要在__new__ 構(gòu)造器中使用threading.Lock() 同步鎖。
定義:
class Singleton(object): ? ? _instance = None ? ? _instance_lock = threading.Lock() ? ? def __new__(cls, *args, **kwargs): ? ? ? ? if cls._instance is None: ? ? ? ? ? ? with cls._instance_lock: ? ? ? ? ? ? ? ? cls._instance = object.__new__(cls, *args, **kwargs) ? ? ? ? return cls._instance
使用:
def task(arg): ? ? instance = Singleton() ? ? print(id(instance), '\n') if __name__ == '__main__': ? ? for i in range(3): ? ? ? ? t = threading.Thread(target=task, args=[i, ]) ? ? ? ? t.start()
到此這篇關(guān)于Python 設(shè)計模式創(chuàng)建型單例模式的文章就介紹到這了,更多相關(guān)Python 單例模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python Web框架Django的模型和數(shù)據(jù)庫遷移詳解
Django 是一個極其強大的 Python Web 框架,它提供了許多工具和特性,能夠幫助我們更快速、更便捷地構(gòu)建 Web 應(yīng)用,在本文中,我們將會關(guān)注 Django 中的模型(Models)和數(shù)據(jù)庫遷移(Database Migrations)這兩個核心概念,需要的朋友可以參考下2023-08-08
TensorFlow卷積神經(jīng)網(wǎng)絡(luò)之使用訓(xùn)練好的模型識別貓狗圖片
今天小編就為大家分享一篇關(guān)于TensorFlow卷積神經(jīng)網(wǎng)絡(luò)之使用訓(xùn)練好的模型識別貓狗圖片,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
python用post訪問restful服務(wù)接口的方法
今天小編就為大家分享一篇python用post訪問restful服務(wù)接口的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12

