日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?設計模式創建型單例模式_python

作者:范桂颶 ? 更新時間: 2022-04-20 編程語言

一、單例模式

單例模式,實現一個類,并且保證這個類的多次實例化操作,都會只生成同一個實例對象。

二、應用場景

整個系統中只需要存在一個實例對象,其他對象都可以通過訪問該對象來獲取信息,比如:

  1. 系統的配置信息對象
  2. 日志對象
  3. 數據庫操作對象
  4. 線程池對象

三、編碼示例

1.單線程中的單例模式

方式一、重載類構造器

定義:

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 個實例對象的內存地址,判斷是否相同。
? ? print(id(instance1))
? ? print(id(instance2))
? ? print(id(instance3))

方式二、實現單例裝飾器

定義:

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.多線程中的單例模式

方式三、重載具有線程鎖的類構造器

多線程中的單例模式,需要在__new__ 構造器中使用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()

原文鏈接:https://is-cloud.blog.csdn.net/article/details/122541891

欄目分類
最近更新