zoukankan      html  css  js  c++  java
  • python单例模式的实现

    1 线程不安全的单例模式

     1 # -*- coding:utf-8 -*-
     2 from __future__ import unicode_literals
     3 
     4 import functools
     5 
     6 
     7 def singleton(func):
     8     """线程不安全的单例模式"""
     9 
    10     @functools.wraps(func)
    11     def wrapper(*args, **kw):
    12         if not hasattr(func, 'singleton_attr'):
    13             func.singleton_attr = func(*args, **kw)
    14         return func.singleton_attr
    15 
    16     return wrapper
    17 
    18 
    19 if __name__ == '__main__':
    20     @singleton
    21     def get_demo_list():
    22         return [1, 2, 3]
    23 
    24 
    25     list_1 = get_demo_list()
    26     list_2 = get_demo_list()
    27     assert id(list_1) == id(list_2)

    2 线程安全的单例模式

     1 # -*- coding:utf-8 -*-
     2 from __future__ import unicode_literals
     3 
     4 import threading
     5 
     6 
     7 class SingletonMixin(object):
     8     """
     9     thread safe singleton base class
    10     refer: https://gist.github.com/werediver/4396488
    11 
    12     # Based on tornado.ioloop.IOLoop.instance() approach.
    13     # See https://github.com/facebook/tornado
    14     """
    15     __singleton_lock = threading.Lock()
    16     __singleton_instance = None
    17 
    18     @classmethod
    19     def instance(cls):
    20         """
    21 
    22         :rtype: SingletonMixin
    23         """
    24         if not cls.__singleton_instance:
    25             with cls.__singleton_lock:
    26                 if not cls.__singleton_instance:
    27                     cls.__singleton_instance = cls()
    28         return cls.__singleton_instance
    29 
    30 
    31 class SingleDemo(SingletonMixin):
    32     def __init__(self):
    33         pass
    34 
    35     @classmethod
    36     def instance(cls):
    37         """
    38 
    39         :rtype: SingleDemo
    40         """
    41         return super(SingleDemo, cls).instance()
    42 
    43 
    44 if __name__ == '__main__':
    45     obj_1 = SingleDemo.instance()
    46     obj_2 = SingleDemo.instance()
    47 
    48     assert id(obj_1) == id(obj_2)
  • 相关阅读:
    PHP——下载图片到本地代码
    PHP接收GET中文参数乱码的原因及解决方案
    防止表单按钮多次提交
    网站页面自动跳转
    php--防止DDos攻击代码
    数据库日期查询存在的问题
    html局部页面打印
    php中::的使用
    php基础:define()定义常数函数
    百度ueditor 拖文件或world 里面复制粘贴图片到编辑中 上传到第三方问题
  • 原文地址:https://www.cnblogs.com/rkfeng/p/8017558.html
Copyright © 2011-2022 走看看