温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Flask框架怎么实现单例模式

发布时间:2021-04-13 16:30:33 来源:亿速云 阅读:503 作者:Leah 栏目:开发技术

使用Flask框架怎么实现单例模式?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

单例模式:

程序运行时只能生成一个实例,避免对同一资源产生冲突的访问请求。

Django   admin.py下的admin.site.register() ,  site就是使用文件导入方式的单例模式

创建到单例模式4种方式:

  • 1.文件导入

  • 2. 类方式

  • 3.基于__new__方式实现

  • 4.基于metaclass方式实现

1.文件导入:

in  single.py

class Singleton():
  def __init__(self):
    pass
site = Singleton()

类似:

import time  第一次已经把导入的time模块,放入内存
import time  第二次内存已有就不导入了

in  app.py

from single.py import site #第一次导入,实例化site对象并放入内存

in  views.py

from single.py import site #第二次导入,直接从内存拿。

2.类方式:

缺点:改变了单例的创建方式

obj = Singleton.instance()
# 单例模式:无法支持多线程情况
import time
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 time
import threading
class Singleton(object):
  _instance_lock = threading.Lock()
  def __init__(self):
    time.sleep(1)
  @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

3.基于__new__方式实现:

单例创建方式:

obj1 = Singleton()
obj2 = Singleton()
import time
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, *args, **kwargs)
    return Singleton._instance

4.基于metaclass方式实现

基于metaclass方式实现的原理:

  • 1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法

  • 2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法

单例创建方式:

obj1 = Foo()
obj2 = Foo()
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):
    pass

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI