import time
import threading
class Singleton(object):
instance = None
lock = threading.RLock()
def __init__(self, name):
"""
初始化对象
"""
self.name = name
def __new__(cls, *args, **kwargs):
"""
创建对象
"""
if cls.instance:
return cls.instance
with cls.lock:
if not cls.instance:
time.sleep(0.02)
cls.instance = object.__new__(cls)
return cls.instance
obj1 = Singleton('zhangyy')
obj2 = Singleton('zhangyy')
print(obj1, obj2)
单例模式
最新推荐文章于 2024-07-25 13:59:31 发布