Python實現單例模式的四種方式詳解

簡介:單例模式可以保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。適用性於當類隻能有一個實例而且客戶可以從一個眾所周知的訪問點訪問它,例如訪問數據庫、MQ等。

實現方式:

1、通過導入模塊實現

2、通過裝飾器實現

3、通過使用類實現

4、通過__new__ 方法實現

單例模塊方式被導入的源碼:singleton.py

# -*- coding: utf-8 -*-
# time: 2022/5/17 10:31
# file: singleton.py
# author: tom
# 公眾號: 玩轉測試開發


class Singleton(object):
    def __init__(self, name):
        self.name = name

    def run(self):
        print(self.name)

s = Singleton("Tom")

主函數源碼:

# -*- coding: utf-8 -*-
# time: 2022/5/17 10:51
# file: test_singleton.py
# author: tom
# 公眾號: 玩轉測試開發
from singleton import s as s1
from singleton import s as s2


# Method One:通過導入模塊實現
def show_method_one():
    """

    :return:
    """
    print(s1)
    print(s2)
    print(id(s1))
    print(id(s2))


show_method_one()


# Method Two:通過裝飾器實現
def singleton(cls):
    # 創建一個字典用來保存類的實例對象
    _instance = {}

    def _singleton(*args, **kwargs):
        # 先判斷這個類有沒有對象
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)  # 創建一個對象,並保存到字典當中
        # 將實例對象返回
        return _instance[cls]

    return _singleton


@singleton
class Demo2(object):
    a = 1

    def __init__(self, x=0):
        self.x = x


a1 = Demo2(1)
a2 = Demo2(2)
print(id(a1))
print(id(a2))


# Method Three:通過使用類實現
class Demo3(object):
    # 靜態變量
    _instance = None
    _flag = False

    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        if not Demo3._flag:
            Demo3._flag = True


b1 = Demo3()
b2 = Demo3()
print(id(b1))
print(id(b2))


# Method Four:通過__new__ 方法實現
class Demo4:
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(Demo4, cls).__new__(cls)
        return cls._instance


c1 = Demo4()
c2 = Demo4()
print(id(c1))
print(id(c2))

運行結果:

到此這篇關於Python實現單例模式的四種方式詳解的文章就介紹到這瞭,更多相關Python單例模式內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: