单例模式创建
4.基于__new__方法实现(推荐使用,方便)
通过上面例子,我们可以知道,当我们实现单例时,为了保证线程安全需要在内部加入锁
我们知道,当我们实例化一个对象时,是先执行了类的__new__方法(我们没写时,默认调用object.__new__),实例化对象;然后再执行类的__init__方法,对这个对象进行初始化,所有我们可以基于这个,实现单例模式
import threading
class SingleType:
_instance = None # 静态字段
_instance_lock = threading.Lock() # 锁 类
def __new__(cls, *args, **kwargs):
if not cls._instance:
with Singleton._instance_lock: # 锁
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
super().__init__()
for i in range(10):
obj = SingleType()
print(obj)
一般使用模块导入的方法
mysingleton.py
class Singleton(object):
def foo(self): pass
singleton = Singleton()
from mysingleton import singleton
浙公网安备 33010602011771号