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

发布于:2025-03-08 ⋅ 阅读:(92) ⋅ 点赞:(0)

各类资料学习下载合集           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. 装饰器:通过装饰器实现。