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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

Python實(shí)現(xiàn)單例模式的四種方式詳解_python

作者:玩轉(zhuǎn)測(cè)試開發(fā) ? 更新時(shí)間: 2022-07-14 編程語(yǔ)言

簡(jiǎn)介:?jiǎn)卫J娇梢员WC一個(gè)類僅有一個(gè)實(shí)例,并提供一個(gè)訪問(wèn)它的全局訪問(wèn)點(diǎn)。適用性于當(dāng)類只能有一個(gè)實(shí)例而且客戶可以從一個(gè)眾所周知的訪問(wèn)點(diǎn)訪問(wèn)它,例如訪問(wèn)數(shù)據(jù)庫(kù)、MQ等。

實(shí)現(xiàn)方式:

1、通過(guò)導(dǎo)入模塊實(shí)現(xiàn)

2、通過(guò)裝飾器實(shí)現(xiàn)

3、通過(guò)使用類實(shí)現(xiàn)

4、通過(guò)__new__ 方法實(shí)現(xiàn)

單例模塊方式被導(dǎo)入的源碼:singleton.py

# -*- coding: utf-8 -*-
# time: 2022/5/17 10:31
# file: singleton.py
# author: tom
# 公眾號(hào): 玩轉(zhuǎn)測(cè)試開發(fā)


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

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

s = Singleton("Tom")

主函數(shù)源碼:

# -*- coding: utf-8 -*-
# time: 2022/5/17 10:51
# file: test_singleton.py
# author: tom
# 公眾號(hào): 玩轉(zhuǎn)測(cè)試開發(fā)
from singleton import s as s1
from singleton import s as s2


# Method One:通過(guò)導(dǎo)入模塊實(shí)現(xiàn)
def show_method_one():
    """

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


show_method_one()


# Method Two:通過(guò)裝飾器實(shí)現(xiàn)
def singleton(cls):
    # 創(chuàng)建一個(gè)字典用來(lái)保存類的實(shí)例對(duì)象
    _instance = {}

    def _singleton(*args, **kwargs):
        # 先判斷這個(gè)類有沒(méi)有對(duì)象
        if cls not in _instance:
            _instance[cls] = cls(*args, **kwargs)  # 創(chuàng)建一個(gè)對(duì)象,并保存到字典當(dāng)中
        # 將實(shí)例對(duì)象返回
        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:通過(guò)使用類實(shí)現(xiàn)
class Demo3(object):
    # 靜態(tài)變量
    _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:通過(guò)__new__ 方法實(shí)現(xiàn)
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))

運(yùn)行結(jié)果:

原文鏈接:https://blog.csdn.net/hzblucky1314/article/details/124833122

欄目分類
最近更新