Python单例模式实现详解:从模块到元类的五种方案与线程安全优化

顾星河
顾星河
发布时间:2026-10-14| 6人浏览过
原创

本文深入解析Python中实现单例模式的多种方法,包括利用模块天然单例、类方法加锁、重写__new__以及基于元类的实现。重点讨论了多线程环境下的竞态条件问题,通过双重检查锁定机制优化线程安全,并对比各方案的优缺点与使用限制,帮助开发者选择最适合场景的单例实现方式。

单例模式概述

单例模式

单例模式(Singleton Pattern)属于常用的软件设计模式之一,其核心目标是确保一个类在整个系统中仅存在一个实例。当业务场景要求某个类只能有一个对象时,单例模式便成为理想选择。

以服务器配置读取为例,假设配置信息存储于文件中,系统通过 AppConfig 类来加载这些内容。若程序运行期间多处需要读取配置,且每次调用都创建新的 AppConfig 实例,将导致内存资源浪费,尤其在配置数据庞大时更为显著。因此,此类场景下应确保 AppConfig 类在程序生命周期内仅维持一个实例。

在 Python 语言中,存在多种技术手段来实现单例模式。

Python单例模式实现方案

实现单例模式的几种方式

基于模块的单例实现

1.使用模块

Python 的模块机制天然支持单例模式。当模块首次被导入时,解释器会生成 .pyc 编译文件;后续再次导入该模块时,直接加载已有的 .pyc 文件,而不会重新执行模块顶层代码。因此,只需将相关函数和数据定义在单一模块中,即可自然获得一个单例对象。若需显式构建单例类,可参考以下实现思路:


mysingleton.py
class Singleton(object):
 def foo(self):
  pass
singleton = Singleton()

将上述代码保存为 mysingleton.py 文件。在使用时,只需在其他文件中导入该模块中的对象实例,该实例即为单例模式的对象。


from a import singleton
 

基于类的单例实现与线程安全优化

2.使用类


class Singleton(object):
 def __init__(self):
 pass
 @classmethod
 def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
  Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance

通常认为上述方式已实现单例,但在多线程并发场景下,这种方式存在潜在问题。


class Singleton(object):
 def __init__(self):
 pass
 @classmethod
 def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
  Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance
import threading
def task(arg):
 obj = Singleton.instance()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()

程序执行后,打印结果如下:


<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>
<__main__.Singleton object at 0x02C933D0>

看似正常,原因在于执行速度极快。若在 __init__ 方法中包含 IO 操作(如文件读取或网络请求),问题便会暴露。下文通过 time.sleep 模拟耗时操作以复现该问题。

我们在上面__init__方法中加入以下代码:


def __init__(self): import time time.sleep(1)

重新执行程序后,结果如下


<__main__.Singleton object at 0x034A3410>
<__main__.Singleton object at 0x034BB990>
<__main__.Singleton object at 0x034BB910>
<__main__.Singleton object at 0x034ADED0>
<__main__.Singleton object at 0x034E6BD0>
<__main__.Singleton object at 0x034E6C10>
<__main__.Singleton object at 0x034E6B90>
<__main__.Singleton object at 0x034BBA30>
<__main__.Singleton object at 0x034F6B90>
<__main__.Singleton object at 0x034E6A90>

问题显现:按上述方式创建的单例,无法支持多线程并发访问。

解决办法:加锁!未加锁部分并发执行,加锁部分串行执行,速度降低,但是保证了数据安全


import time
import threading
class Singleton(object):
 _instance_lock = threading.Lock()
 def __init__(self):
 time.sleep(1)
 @classmethod
 def instance(cls, *args, **kwargs):
 with Singleton._instance_lock:
  if not hasattr(Singleton, "_instance"):
  Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance

def task(arg):
 obj = Singleton.instance()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)

打印结果如下:


<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>
<__main__.Singleton object at 0x02D6B110>

基本功能已实现,但仍存在细微缺陷。当程序执行 time.sleep(20) 后,后续实例化对象时,单例已存在,但此时仍会尝试获取锁,造成不必要的开销。进一步优化 instance 方法,改为如下形式即可:


@classmethod
 def instance(cls, *args, **kwargs):
 if not hasattr(Singleton, "_instance"):
  with Singleton._instance_lock:
  if not hasattr(Singleton, "_instance"):
   Singleton._instance = Singleton(*args, **kwargs)
 return Singleton._instance

这样,一个可以支持多线程的单例模式就完成了


import time
import threading
class Singleton(object):
 _instance_lock = threading.Lock()
 def __init__(self):
  time.sleep(1)
 @classmethod
 def instance(cls, *args, **kwargs):
  if not hasattr(Singleton, "_instance"):
   with Singleton._instance_lock:
    if not hasattr(Singleton, "_instance"):
     Singleton._instance = Singleton(*args, **kwargs)
  return Singleton._instance

def task(arg):
 obj = Singleton.instance()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)

这种方式实现的单例模式,使用时会有限制,以后实例化必须通过 obj = Singleton.instance()

如果用 obj=Singleton() ,这种方式得到的不是单例

基于__new__方法的单例实现

3.基于__new__方法实现(推荐使用,方便)

通过上述示例可知,实现单例时为保证线程安全,需在内部加入锁机制。

我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式


import threading
class Singleton(object):
 _instance_lock = threading.Lock()
 def __init__(self):
  pass

 def __new__(cls, *args, **kwargs):
  if not hasattr(Singleton, "_instance"):
   with Singleton._instance_lock:
    if not hasattr(Singleton, "_instance"):
     Singleton._instance = object.__new__(cls, *args, **kwargs)
  return Singleton._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1,obj2)
def task(arg):
 obj = Singleton()
 print(obj)
for i in range(10):
 t = threading.Thread(target=task,args=[i,])
 t.start()

打印结果如下:


<__main__.Singleton object at 0x038B33D0> <__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>
<__main__.Singleton object at 0x038B33D0>

采用这种方式的单例模式,以后实例化对象时,和平时实例化对象的方法一样 obj = Singleton()

基于元类的单例实现

4.基于metaclass方式实现

相关知识


"""
1.类由type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)
2.对象由类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
"""

例子:


class Foo:
 def __init__(self):
  pass
 def __call__(self, *args, **kwargs):
  pass
obj = Foo()
# 执行type的 __call__ 方法,调用 Foo类(是type的对象)的 __new__方法,用于创建对象,然后调用 Foo类(是type的对象)的 __init__方法,用于对对象初始化。
obj() # 执行Foo的 __call__ 方法

元类的使用


class SingletonType(type):
 def __init__(self,*args,**kwargs):
  super(SingletonType,self).__init__(*args,**kwargs)
 def __call__(cls, *args, **kwargs): # 这里的cls,即Foo类
  print('cls',cls)
  obj = cls.__new__(cls,*args, **kwargs)
  cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
  return obj
class Foo(metaclass=SingletonType): # 指定创建Foo的type为SingletonType
 def __init__(self):
  pass
 def __new__(cls, *args, **kwargs):
  return object.__new__(cls, *args, **kwargs)
obj = Foo()

实现单例模式


import threading
class SingletonType(type):
 _instance_lock = threading.Lock()
 def __call__(cls, *args, **kwargs):
  if not hasattr(cls, "_instance"):
   with SingletonType._instance_lock:
    if not hasattr(cls, "_instance"):
     cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
  return cls._instance
class Foo(metaclass=SingletonType):
 def __init__(self,name):
  self.name = name

obj1 = Foo('name')
obj2 = Foo('name')
print(obj1,obj2)

以上这篇基于Python中单例模式的几种实现方式及优化详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持本站。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。