深入理解设计模式中的单例模式(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. 装饰器:通过装饰器实现。
相关推荐
书院门前细致的苹果13 小时前
设计模式大全:单例、工厂模式、策略模式、责任链模式
设计模式·责任链模式·策略模式
有位神秘人1 天前
kotlin与Java中的单例模式总结
java·单例模式·kotlin
BD_Marathon1 天前
设计模式——依赖倒转原则
java·开发语言·设计模式
BD_Marathon1 天前
设计模式——里氏替换原则
java·设计模式·里氏替换原则
jmxwzy1 天前
设计模式总结
设计模式
J_liaty2 天前
23种设计模式一代理模式
设计模式·代理模式
苏渡苇2 天前
优雅应对异常,从“try-catch堆砌”到“设计驱动”
java·后端·设计模式·学习方法·责任链模式
短剑重铸之日2 天前
《设计模式》第十一篇:总结
java·后端·设计模式·总结
feasibility.2 天前
AI 编程助手进阶指南:从 Claude Code 到 OpenCode 的工程化经验总结
人工智能·经验分享·设计模式·自动化·agi·skills·opencode
BD_Marathon2 天前
七大设计原则介绍
设计模式