在flask实现单例模式的方法有多种:

这里我们列举五种,行吗?

 

第一种:

  国际惯例:基于文件导入

 

第二种:

  基于类的单例模式:

    它又分两种: 一种加锁,一种不加锁。

          不加锁的话,可以并发,但是我们的初衷是单例。

          加了锁的话,可以多线程,缺陷也很明显 看代码

# 单例模式:无法支持多线程情况
# class Singleton(object):
#     def __init__(self):
#         import time
#         time.sleep(1)
#
#     @classmethod
#     def instance(cls,*args,**kwargs):
#         if not hasattr(Singleton,'_instance')
#             # 每一个线程来,创建了一次
#             Singleton._instance = Singleton(*args,**kwargs)
#         return Singleton._instance
#
# import threading
#
# def task(arg):
#     obj = Singleton.instance()
#     print(obj)
# for i in range(4):
#     t = threading.Thread(target=task,args=[i,])
#     t.start()
"""
<__main__.Singleton object at 0x10225e240>
<__main__.Singleton object at 0x10227ddd8>
<__main__.Singleton object at 0x10227deb8>
<__main__.Singleton object at 0x1022a25c0>
"""


# 单例模式:支持多线程(加锁!!!!!!!)
# 该方法的缺陷: 要告诉使用者,以后使用单例模式,要用Singleton.instance()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
import time
import threading
class Singleton:
    def __init__(self):
        time.sleep(1)
    _instance_lock = threading.Lock()
    @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()
"""
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
<__main__.Singleton object at 0x102265160>
"""
鸡鱼类的两种单例

相关文章:

  • 2021-10-28
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
  • 2021-12-03
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2021-09-21
  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案