深入理解设计模式中的单例模式(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. 装饰器:通过装饰器实现。
相关推荐
叫我龙翔2 小时前
【设计模式】从游戏角度开始了解设计模式 --- 抽象工厂模式
c++·游戏·设计模式
青草地溪水旁2 小时前
设计模式(C++)详解—单例模式(1)
c++·单例模式
库奇噜啦呼5 小时前
【iOS】单例模式
ios·单例模式
馨谙5 小时前
设计模式之单例模式大全---java实现
java·单例模式·设计模式
土了个豆子的19 小时前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
Buling_021 小时前
游戏中的设计模式——第三篇 简单工厂模式
游戏·设计模式·简单工厂模式
饭碗的彼岸one21 小时前
C++设计模式之单例模式
c语言·开发语言·c++·单例模式·设计模式·饿汉模式·懒汉模式
麦当_1 天前
TanStack Router File-Based Router Mask 完全指南
前端·javascript·设计模式
烛阴1 天前
【TS 设计模式完全指南】用适配器模式优雅地“兼容”一切
javascript·设计模式·typescript
青草地溪水旁1 天前
23 种设计模式
开发语言·c++·设计模式