深入理解设计模式中的单例模式(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. 装饰器:通过装饰器实现。
相关推荐
黄明基3 小时前
设计模式学习:2、状态模式实现订单状态流转
设计模式·.net·dotnet core
JuicyActiveGilbert4 小时前
【C++设计模式】第一篇:单例模式(Singleton)
c++·单例模式·设计模式
小马爱打代码4 小时前
设计模式详解(单例模式)
java·单例模式·设计模式
码熔burning5 小时前
(二 十 三)趣学设计模式 之 解释器模式!
java·设计模式·解释器模式
新停浊酒杯5 小时前
设计模式——代理模式(Proxy)
设计模式·代理模式
Nita.6 小时前
设计模式|策略模式 Strategy Pattern 详解
设计模式·c#·策略模式
攻城狮7号6 小时前
【第15节】C++设计模式(行为模式)-State(状态)模式
c++·设计模式·状态模式
JuicyActiveGilbert7 小时前
【C++设计模式】第五篇:原型模式(Prototype)
c++·设计模式·原型模式
述雾学java7 小时前
多线程的使用、同步和异步、synchronized、线程安全的单例模式、死锁、解决死锁
java·python·单例模式