单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类 只有一个实例对象 存在。
实现单例模式的几种方式
1.基于 __new__ 方法实现(推荐使用,简单方便)
class single_instance(object):
__instance = None
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if cls.__instance == None:
cls.__instance = object.__new__(cls,*args,**kwargs)
return cls.__instance
2. 使用模块
Python 的模块就是天然的单例模式,因为模块在第一次导入时,会生成 .pyc 文件,当第二次导入时,就会直接加载 .pyc 文件,而不会再次执行模块代码。因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。
============= mysingleton.py ==================
class Singleton(object):
def fan(self):
pass
singleton = Singleton() #<<<=====实例化对象
================ end =========================
from . import singleton #<<<====引入单例对象
3.使用装饰器
python装饰器就是用于拓展原函数功能的一种函数,这个函数的特殊之处在于它的返回值也是一个函数(闭包),使用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 fan(object):
def __init__(self, x=0):
self.x = x
a1 = fan(2)
print(a1.x) #2
a2 = fan(3)
print(a1.x) #2
print(a2.x) #2
4.使用类
import threading #为了保证线程安全需要在内部加入锁
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
@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()
obj = Singleton.instance()
print(obj)
这种方式实现的单例模式,使用时会有限制,以后实例化必须通过 obj = Singleton.instance()
如果用 obj=Singleton() ,这种方式得到的不是单例
5.改造 __new__ 方法(推荐使用)
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)
return Singleton._instance
def task(arg):
obj = Singleton()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
6.基于 元类(metaclass)实现
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)