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)
  • 相关阅读:
    微软官方Silverlight5新特性完整介绍
    Windows Phone 7外包(承接WP7项目外包 可签合同 长期有效)
    我们为什么要选择Silverlight?(CSDN网友的见解分享大家)【转】
    开博记录02120928
    [转载]在linux下如何制作img的映像文件
    JavaScript中的null和undefined
    年度映像
    25岁毕业,拿一万块钱月薪
    saymedia bug问题
    mxp组件开发及jsfl文件
  • 原文地址:https://www.cnblogs.com/rkfeng/p/8017558.html
Copyright © 2011-2022 走看看