网站首页 > 基础教程 正文
为什么选择单例模式
单例模式是一种常见的软件设计模式,其主要目的是确保一个类只有一个实例存在。当您希望一个类的一个实例只出现在整个系统中时,单例对象就派上用场了。
例如,一个服务器程序的配置信息保存在一个文件中,客户端通过一个AppConfig类来读取配置文件信息。
如果程序运行过程中需要在多处使用配置文件的内容,也就是说AppConfig需要在多处创建对象的实例,导致AppConfig系统中存在多个实例对象,会严重浪费内存资源,尤其是配置文件内容很多的情况下。
事实上,对于像这样的类AppConfig,我们希望在程序运行期间只存在一个对象实例。
在 Python 中编写单例的 5 种方法
在 Python 中,我们可以通过几种方式实现单例模式:
使用模块
其实Python的模块是天生的单例模式,因为第一次导入模块时,会生成一个.pyc文件,第二次导入时,.pyc直接加载文件,不会再次执行模块代码.
因此,我们只需要在一个模块中定义相关的函数和数据就可以得到一个单例对象。如果我们真的想要一个单例类,可以考虑这样做:
class Singleton(object):
def foo(self):
pass
singleton = Singleton()
把上面的代码保存在文件mysingleton.py中,当你要使用的时候,直接在其他文件中导入这个文件中的对象,这个对象就是单例模式的对象。
from mysingleton import singleton
使用装饰器
装饰器可用于将函数和类包装或封装在@包装器中。如果您想了解更多细节,请查看我的 Python 装饰器文章:“ ”。
Decorator修饰的类或函数,本质上已经不是原来的类或函数了。但实际上,包装后的新对象仍然具有被包装对象的属性。
在Python中,我们往往只需要实现一个装饰器,然后使用装饰器作用于一个只有一个实例的类。这样,你只需要实现这样一个装饰器就可以作用于任何你想要拥有唯一实例的类。
def Singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
a = 1
def __init__(self, x=0):
self.x = x
a1 = A(2)
a2 = A(3)
函数声明了一个属于函数作用域的局部Singleton变量。每次调用都会创建一个新的独立函数(所谓的闭包)。
_instancesSingletonSingleton_singleton
根据 LEGB 规则,封闭范围的变量是“继承”(这在技术上是不正确的,但简化了解释)到闭包。这意味着,_instances对于特定_singleton()函数的每次调用都将保持相同的对象。
由于每次调用A()actually_singletion被调用,并且_instances每次调用此特定函数都保持不变_singleton,我们可以实现这样的效果,即只创建一次类,并且每次后续调用都将返回相同的对象。
使用类方法
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()
程序执行后,打印结果如下:
好像没什么问题,那是因为执行速度太快了,如果__init__方法里面有一些IO操作,就会发现问题。
time.sleep下面我们模拟一下,我们在上面的方法中加入如下代码:__init__
class Singleton(object):
def __init__(self):
import time
time.sleep(1)
@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()
重新执行程序后,结果如下:
出现问题!上述方式创建的单例不支持多线程。
解决办法:锁定它!解锁部分并发执行,加锁部分串行执行,降低了速度,但保证了数据安全。
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)
重新执行程序后,结果如下:
使用“__new__”方法
从上面的例子我们可以知道,我们在实现单例的时候,为了保证线程安全,需要在内部加一把锁。
我们知道,当我们实例化一个对象时,首先会执行__new__类的方法(没写的时候默认调用object.__new__),实例化对象;然后执行__init__类的方法来初始化对象,我们可以做的都是基于this,实现了单例模式。
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)
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()
打印结果如下:
这样使用单例模式,以后实例化对象的时候,实例化对象的方法和平时一样obj = Singleton()。
使用元类
首先我们需要明白:
- 类是由类型创建的。创建类时__init__自动执行该class()类型的方法,执行该类型__call__的方法(类的__new__方法,类的方法__init__)
- 对象由类创建。对象创建时__init__自动执行类的方法,object()执行__call__类的方法
例如:
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
pass
# Execute Type's __call__ method, call Foo.__new__() to create object, then call Foo.__init__() to initialize
obj = Foo()
# Execute Foo.__call__ method
obj()
实现单例:
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)
运行输出:
如果你发现我的任何文章对你有帮助或者有用,麻烦点赞或者转发。 谢谢!
- 上一篇: Spring学习之路——单例模式和多例模式
- 下一篇: 在Java中,如何实现线程安全的单例模式?
猜你喜欢
- 2025-06-18 单例模式谁都会,破坏单例模式听说过吗?
- 2025-06-18 Objective-c单例模式的正确写法「藏」
- 2025-06-18 单例模式介绍(单例模式都有哪些)
- 2025-06-18 前端设计-单例模式在实战中的应用技巧
- 2025-06-18 PHP之单例模式(php单例模式连接数据库)
- 2025-06-18 设计模式:单例模式及C及C++实现示例
- 2025-06-18 python的单例模式(单例 python)
- 2025-06-18 你认为最简单的单例模式,东西还挺多
- 2025-06-18 Python入门题037:实现单例类(3种方法)
- 2025-06-18 用好单例设计模式,也可以让你的代码性能提升300%
- 06-18单例模式谁都会,破坏单例模式听说过吗?
- 06-18Objective-c单例模式的正确写法「藏」
- 06-18单例模式介绍(单例模式都有哪些)
- 06-18前端设计-单例模式在实战中的应用技巧
- 06-18PHP之单例模式(php单例模式连接数据库)
- 06-18设计模式:单例模式及C及C++实现示例
- 06-18python的单例模式(单例 python)
- 06-18你认为最简单的单例模式,东西还挺多
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- 单例 (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)