单例模式的实现方式
一 何为单例模式
单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在。当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场。
比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息。如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪费内存资源,尤其是在配置文件内容很多的情况下。事实上,类似 AppConfig 这样的类,我们希望在程序运行期间只存在一个实例对象。
二 单例模式的实现
2.1 使用模块
Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象
class MySingleton(object):
def __int__(self):
pass
def foo(self):
pass
singleton = MySingleton()将以上代码保存在一个py文件中,比如:my_singleton.py,需要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象
from xxx.adminplugin import singleton
2.2 使用装饰器
def my_singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@my_singleton
class Foo(object):
def __init__(self):
pass
f1 = Foo()
f2 = Foo()
print(f1) # <__main__.Foo object at 0x000001D973B7B4E0>
print(f2) # <__main__.Foo object at 0x000001D973B7B4E0>2.3 使用类
class MySingleton(object):
def __init__(self):
pass
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = cls(*args, **kwargs)
return cls._instance
singleton1 = MySingleton.instance()
singleton2 = MySingleton.instance()
print(singleton1) # <__main__.MySingleton object at 0x0000021343DFB1D0>
print(singleton2) # <__main__.MySingleton object at 0x0000021343DFB1D0>这种方式下,使用多线程时会存在问题
class MySingleton(object):
def __init__(self):
pass
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = cls(*args, **kwargs)
return cls._instance
import threading
def task(arg):
obj = MySingleton.instance()
print(obj)
for i in range(5):
t = threading.Thread(target=task,args=[i,])
t.start()执行结果为:
<__main__.MySingleton object at 0x00000251174CB2B0> <__main__.MySingleton object at 0x00000251174CB2B0> <__main__.MySingleton object at 0x00000251174CB2B0> <__main__.MySingleton object at 0x00000251174CB2B0> <__main__.MySingleton object at 0x00000251174CB2B0>
看起来也没有问题,那是因为执行速度过快,如果在init方法中有一些IO操作,就会发现问题了,下面我们通过time.sleep模拟
我们在上面__init__方法中加入以下代码:
def __init__(self):
import time
time.sleep(1)执行结果为:
<__main__.MySingleton object at 0x000001BDB4A00CC0> <__main__.MySingleton object at 0x000001BDB4A00F60> <__main__.MySingleton object at 0x000001BDB485A2B0> <__main__.MySingleton object at 0x000001BDB4A00DA0> <__main__.MySingleton object at 0x000001BDB4A11160>
问题出现了!按照以上方式创建的单例,无法支持多线程
解决办法:加锁!未加锁部分并发执行,加锁部分串行执行,速度降低,但是保证了数据安全
import threading
import time
class MySingleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
with MySingleton._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = cls(*args, **kwargs)
return cls._instance
def task(arg):
obj = MySingleton.instance()
print(obj)
for i in range(5):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(5)
obj = MySingleton.instance()
print(obj)执行结果为:
<__main__.MySingleton object at 0x000002E4A1FB9B70> <__main__.MySingleton object at 0x000002E4A1FB9B70> <__main__.MySingleton object at 0x000002E4A1FB9B70> <__main__.MySingleton object at 0x000002E4A1FB9B70> <__main__.MySingleton object at 0x000002E4A1FB9B70> <__main__.MySingleton object at 0x000002E4A1FB9B70>
这样就差不多了,但是还是有一点小问题,就是当程序执行时,执行了time.sleep(5)后,下面实例化对象时,此时已经是单例模式了,但我们还是加了锁,这样不太好,再进行一些优化,把intance方法,改成下面的这样就行:
@classmethod
def instance(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with MySingleton._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = cls(*args, **kwargs)
return cls._instance这样,一个可以支持多线程的单例模式就完成了
import threading import time class MySingleton(object): _instance_lock = threading.Lock() def __init__(self): time.sleep(1) @classmethod def instance(cls, *args, **kwargs): if not hasattr(cls, "_instance"): with MySingleton._instance_lock: if not hasattr(cls, "_instance"): cls._instance = cls(*args, **kwargs) return cls._instance def task(arg): obj = MySingleton.instance() print(obj) for i in range(5): t = threading.Thread(target=task,args=[i,]) t.start() time.sleep(5) obj = MySingleton.instance() print(obj)
这种方式实现的单例模式,使用时会有限制,以后实例化必须通过
obj = MySingleton.instance()
如果用 obj=MySingleton() ,这种方式得到的不是单例
2.4 使用__new__方法实现(推荐使用)
通过上面例子,我们可以知道,当我们实现单例时,为了保证线程安全需要在内部加入锁
我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式
import threading
class MySingleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with cls._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = object.__new__(cls)
return cls._instance
singleton1 = MySingleton()
singleton2 = MySingleton()
print(singleton1)
print(singleton1)
def task(arg):
obj = MySingleton()
print(obj)
for i in range(5):
t = threading.Thread(target=task,args=[i,])
t.start()执行结果为:
<__main__.MySingleton object at 0x000001AEE10F4978> <__main__.MySingleton object at 0x000001AEE10F4978> <__main__.MySingleton object at 0x000001AEE10F4978> <__main__.MySingleton object at 0x000001AEE10F4978> <__main__.MySingleton object at 0x000001AEE10F4978> <__main__.MySingleton object at 0x000001AEE10F4978> <__main__.MySingleton object at 0x000001AEE10F4978>
采用这种方式的单例模式,以后实例化对象时,和平时实例化对象的方法一样:obj = MySingleton()即可
2.5 基于metaclass方式实现
相关知识了解:
- 类由type创建,创建类时,type的__init__方法自动执行,类() 执行type的 __call__方法(类的__new__方法,类的__init__方法)
- 对象由类创建,创建对象时,类的__init__方法自动执行,对象()执行类的 __call__ 方法
class Foo(object):
def __init__(self):
print('init')
def __call__(self, *args, **kwargs):
print('call')
# 执行type的 __call__ 方法
# 调用Foo类(type的对象)的 __new__方法,用于创建对象,注意:如果要得到当前类的实例,应当在当前类中的__new__()方法语句中调用当前类的父类的__new__()方法
# 调用Foo类(type的对象)的 __init__方法,用于对对象初始化
obj = Foo() # init
# 执行Foo的 __call__方法
obj() # call元类的使用
class MySingletonType(type): def __init__(self,*args,**kwargs): print('MySingletonType-init') super(MySingletonType,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=MySingletonType): # 指定创建Foo的type为MySingletonType def __init__(self,name): print('Foo-init') self.name = name def __new__(cls, *args, **kwargs): print('Foo-new') return object.__new__(cls) obj = Foo('xxx')
实现单例模式
import threading
class MySingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with MySingletonType._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(MySingletonType,cls).__call__(*args, **kwargs)
return cls._instance
class Foo(metaclass=MySingletonType):
def __init__(self,name):
self.name = name
obj1 = Foo('xxx')
obj2 = Foo('ooo')
print(obj1) # <__main__.Foo object at 0x0000028F48644978>
print(obj2) # <__main__.Foo object at 0x0000028F48644978>
浙公网安备 33010602011771号