深入理解设计模式中的单例模式(Singleton Pattern)

各类资料学习下载合集 https://pan.quark.cn/s/8c91ccb5a474

单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供全局访问点。这种模式在许多应用场景中都很有用,特别是当我们希望控制对共享资源的访问时,比如数据库连接、日志记录器或配置对象。

本文将详细介绍单例模式的概念、实现方式,以及在 Python 中的最佳实践,配合详细的代码示例和运行结果。

一、什么是单例模式?

单例模式的关键要点包括:

  1. 唯一性:确保类只有一个实例。
  2. 全局访问:提供访问该实例的全局点。
  3. 懒加载:实例在首次使用时才创建。

应用场景

  • 数据库连接池
  • 日志记录器
  • 配置管理器
  • 缓存管理

二、实现单例模式

在 Python 中,我们可以使用多种方式实现单例模式,下面将介绍几种常见的方法。

方法 1:使用模块

在 Python 中,每个模块只有一个实例,因此可以直接利用这一特性来实现单例模式。

复制代码
# singleton.py

class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value
使用示例:
复制代码
# main.py

from singleton import Singleton

singleton1 = Singleton()
singleton2 = Singleton()

singleton1.set_value("Singleton Instance")

print(singleton1.get_value())  # 输出:Singleton Instance
print(singleton2.get_value())  # 输出:Singleton Instance
print(singleton1 is singleton2)  # 输出:True

运行结果:

复制代码
Singleton Instance
Singleton Instance
True

分析:

  • 由于 Python 模块的特性,​Singleton​ 类的实例在模块内是唯一的。

方法 2:使用类变量

我们可以使用类变量来保存单例实例。

复制代码
class Singleton:
    _instance = None

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

    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value
使用示例:
复制代码
# main.py

singleton1 = Singleton()
singleton2 = Singleton()

singleton1.set_value("Singleton Instance")

print(singleton1.get_value())  # 输出:Singleton Instance
print(singleton2.get_value())  # 输出:Singleton Instance
print(singleton1 is singleton2)  # 输出:True

运行结果:

复制代码
Singleton Instance
Singleton Instance
True

分析:

  • ​__new__​ 方法用于控制实例的创建。只有在 ​_instance​​None​ 时才创建新的实例,随后返回已存在的实例。

方法 3:使用装饰器

我们还可以使用装饰器来实现单例模式。

复制代码
def singleton(cls):
    instances = {}
    
    def get_instance(*args, **kwargs):
        if cls not in instances:
            instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    
    return get_instance


@singleton
class Singleton:
    def __init__(self):
        self.value = None

    def set_value(self, value):
        self.value = value

    def get_value(self):
        return self.value
使用示例:
复制代码
# main.py

singleton1 = Singleton()
singleton2 = Singleton()

singleton1.set_value("Singleton Instance")

print(singleton1.get_value())  # 输出:Singleton Instance
print(singleton2.get_value())  # 输出:Singleton Instance
print(singleton1 is singleton2)  # 输出:True

运行结果:

复制代码
Singleton Instance
Singleton Instance
True

分析:

  • 通过装饰器将类转化为单例,利用字典 ​instances​ 存储类实例,确保每个类只被实例化一次。

三、总结

单例模式在 Python 中是一种相对简单的创建型设计模式,通过确保类只有一个实例,提供了一个全局访问点。我们探讨了几种实现单例模式的方法,包括:

  1. 模块单例:利用模块的唯一性。
  2. 类变量:在类中控制实例的创建。
  3. 装饰器:通过装饰器实现。
相关推荐
蓝瑟18 分钟前
告别重复造轮子!业务组件多场景复用实战指南
前端·javascript·设计模式
Arva .3 小时前
讲一下 Spring 中用到的设计模式
java·spring·设计模式
繁华似锦respect4 小时前
lambda表达式中的循环引用问题详解
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
星月IWJ7 小时前
领域驱动设计学习
java·学习·设计模式
_dindong8 小时前
Linux网络编程:Reactor反应堆模式
linux·服务器·网络·设计模式·php
雨中飘荡的记忆9 小时前
Step Builder模式实战
java·设计模式
Eren7Y琳9 小时前
开箱即用构建应用环境:openEuler易获得性深度验证
redis·设计模式·架构
Unstoppable229 小时前
八股训练营第 39 天 | Bean 的作用域?Bean 的生命周期?Spring 循环依赖是怎么解决的?Spring 中用到了那些设计模式?
java·spring·设计模式
闲人编程10 小时前
微服务API网关设计模式
python·缓存·微服务·设计模式·系统安全·api·codecapsule
__万波__10 小时前
二十三种设计模式(八)--装饰器模式
java·设计模式·装饰器模式