实现单例模式的方式2
2018-08-14 本文已影响0人
陆_志东
方式一: 能保证线程安全
定义类的时候实现单例模式
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1) # 这里添加耗时操作,是演示不加线程锁的情况下,会出现创建多个实例的情况
@classmethod
def instance(cls, *args, **kwargs):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
def task():
obj = Singleton.instance()
print(id(obj))
list1 = list()
for i in range(10):
t = threading.Thread(target=task)
t.start()
list1.append(t)
for i in list1:
i.join()
obj = Singleton.instance()
print(obj)
方式二: 能保证线程安全
对已定义好的类实现单例模式
# 装饰器的方法实现类的单例模式
from functools import wraps
import threading
global_lock = threading.Lock() # 制定一个全局锁
def sington(cls):
_instances = {}
@wraps(cls)
def wrapper(*args,**kwargs):
with global_lock:
if cls not in _instances:
_instances[cls] = cls(*args,**kwargs)
return _instances[cls]
return wrapper
@sington
class Test:
def __init__(self,*args,**kwargs):
pass
test1 = Test()
test2 = Test()
print(id(test1) == id(test2)) # True