Python 单例模式讲解和代码示例

简介: Python 单例模式讲解和代码示例

使用示例许多开发者将单例模式视为一种反模式 因此它在 Python 代码中的使用频率正在逐步减少

识别方法单例可以通过返回相同缓存对象的静态构建方法来识别

01基础单例


实现一个粗糙的单例非常简单 你仅需隐藏构造函数并实现一个静态的构建方法即可

相同的类在多线程环境中会出错 多线程可能会同时调用构建方法并获取多个单例类的实例

main.py: 概念示例


classSingletonMeta(type):

 

"""
    The Singleton class can be implemented in different ways in Python. Some
    possible methods include: base class, decorator, metaclass. We will use the
    metaclass because it is best suited for this purpose.
    """
    _instances = {}
    def __call__(cls, *args, **kwargs):
        """
        Possible changes to the value of the `__init__` argument do not affect
        the returned instance.
        """
        if cls not in cls._instances:
            instance = super().__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
    def some_business_logic(self):
        """
        Finally, any singleton should define some business logic, which can be
        executed on its instance.
        """
        #...
if __name__ == "__main__":
    #The client code.
    s1 = Singleton()
    s2 = Singleton()
    if id(s1) == id(s2):
        print("Singleton works, both variables contain the same instance.")
    else:
        print("Singleton failed, variables contain different instances.")

 Output.txt: 执行结果

Singleton works, both variables contain the same instance.

02线程安全单例


为了解决这个问题 你必须在创建首个单例对象时对线程进行同步

main.py: 概念示例

from threading import Lock, Thread
class SingletonMeta(type):
    """
    This is a thread-safe implementation of Singleton.
    """
    _instances = {}
    _lock: Lock = Lock()
    """
    We now have a lock object that will be used to synchronize threads during
    first access to the Singleton.
    """
    def __call__(cls, *args, **kwargs):
        """
        Possible changes to the value of the `__init__` argument do not affect
        the returned instance.
        """
        #Now, imagine that the program has just been launched. Since there's no
        #Singleton instance yet, multiple threads can simultaneously pass the
        #previous conditional and reach this point almost at the same time. The
        #first of them will acquire lock and will proceed further, while the
        #rest will wait here.
        with cls._lock:
            #The first thread to acquire the lock, reaches this conditional,
            #goes inside and creates the Singleton instance. Once it leaves the
            #lock block, a thread that might have been waiting for the lock
            #release may then enter this section. But since the Singleton field
            #is already initialized, the thread won't create a new object.
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
        return cls._instances[cls]
class Singleton(metaclass=SingletonMeta):
    value: str = None
    """
    We'll use this property to prove that our Singleton really works.
    """
    def __init__(self, value: str) -> None:
        self.value = value
    def some_business_logic(self):
        """
        Finally, any singleton should define some business logic, which can be
        executed on its instance.
        """
def test_singleton(value: str) -> None:
    singleton = Singleton(value)
    print(singleton.value)
if __name__ == "__main__":
    #The client code.
    print("If you see the same value, then singleton was reused (yay!)\n"
          "If you see different values, "
          "then 2 singletons were created (booo!!)\n\n"
          "RESULT:\n")
    process1 = Thread(target=test_singleton, args=("FOO",))
    process2 = Thread(target=test_singleton, args=("BAR",))
    process1.start()
    process2.start()

Output.txt: 执行结果

If you see the same value, then singleton was reused (yay!)
If you see different values, then 2 singletons were created (booo!!)
RESULT:
FOO
FOO
相关文章
|
7天前
|
机器学习/深度学习 人工智能 算法
机械视觉:原理、应用及Python代码示例
机械视觉:原理、应用及Python代码示例
|
6天前
|
机器学习/深度学习 自然语言处理 数据可视化
数据代码分享|PYTHON用NLP自然语言处理LSTM神经网络TWITTER推特灾难文本数据、词云可视化
数据代码分享|PYTHON用NLP自然语言处理LSTM神经网络TWITTER推特灾难文本数据、词云可视化
21 1
|
7天前
|
机器学习/深度学习 人工智能 自动驾驶
人工智能:原理、应用与Python代码实现
人工智能:原理、应用与Python代码实现
|
2天前
|
自然语言处理 数据可视化 数据挖掘
数据代码分享|Python对全球Covid-19疫情失业数据相关性、可视化分析
数据代码分享|Python对全球Covid-19疫情失业数据相关性、可视化分析
|
2天前
|
Serverless Python
使用Python的pandas和matplotlib库绘制移动平均线(MA)示例
使用Python的pandas和matplotlib库绘制移动平均线(MA)示例:加载CSV数据,计算5日、10日和20日MA,然后在K线图上绘制。通过`rolling()`计算平均值,`plot()`函数展示图表,`legend()`添加图例。可利用matplotlib参数自定义样式。查阅matplotlib文档以获取更多定制选项。
13 1
|
2天前
|
安全 网络安全 Python
使用 Python 代码实现 ICMP Timestamp 请求和回应
使用 Python 代码实现 ICMP Timestamp 请求和回应
|
3天前
|
Linux iOS开发 MacOS
pyinstaller---Python代码的打包神器,一键将python代码打包成exe可执行文件
pyinstaller---Python代码的打包神器,一键将python代码打包成exe可执行文件
|
3天前
|
缓存 Python
Python 中的装饰器:提升代码可读性和灵活性的利器
装饰器是 Python 中一种强大的工具,它能够在不修改原有代码的情况下,增加新的功能和行为。本文将深入探讨装饰器的原理、用法以及在实际开发中的应用场景,帮助读者更好地理解并运用装饰器来提升代码的可读性和灵活性。
|
4天前
|
存储 算法 搜索推荐
如何提升Python代码的性能:优化技巧与实践
本文将介绍如何通过优化技巧和实践方法来提升Python代码的性能。从避免不必要的循环和函数调用,到利用内置函数和库,再到使用适当的数据结构和算法,我们将深入探讨各种提升Python代码性能的方法,帮助开发者写出更高效的程序。
|
4天前
|
算法 Python
优化Python代码的五大技巧
在日常的Python编程中,优化代码是提高性能和效率的关键。本文介绍了五大实用技巧,包括使用内置函数、避免不必要的循环、利用列表推导式、使用生成器和考虑算法复杂度。通过掌握这些技巧,可以使Python代码更加高效、简洁和可维护。