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)
  • 相关阅读:
    上学要迟到了【最短路转化】
    解方程【狄利克雷卷积+莫比乌斯反演+积性函数】
    FFT
    min25 筛
    Easy【生成函数】
    CF1406D-Three Sequences
    Alice和Bob赌糖果【赌徒破产模型】
    记MySQL自增主键修改无效的问题
    JVM学习笔记(十一、JDK分析工具)
    JVM学习笔记(十、GC3-垃圾回收机制)
  • 原文地址:https://www.cnblogs.com/rkfeng/p/8017558.html
Copyright © 2011-2022 走看看