zoukankan      html  css  js  c++  java
  • Python单例模式研究

    方法一

    Python代码  收藏代码
    1. import threading  
    2.   
    3. class Singleton(object):  
    4.     __instance = None  
    5.   
    6.     __lock = threading.Lock()   # used to synchronize code  
    7.   
    8.     def __init__(self):  
    9.         "disable the __init__ method"  
    10.  
    11.     @staticmethod  
    12.     def getInstance():  
    13.         if not Singleton.__instance:  
    14.             Singleton.__lock.acquire()  
    15.             if not Singleton.__instance:  
    16.                 Singleton.__instance = object.__new__(Singleton)  
    17.                 object.__init__(Singleton.__instance)  
    18.             Singleton.__lock.release()  
    19.         return Singleton.__instance  

     1.禁用__init__方法,不能直接创建对象。

     2.__instance,单例对象私有化。

     3.@staticmethod,静态方法,通过类名直接调用。

     4.__lock,代码锁。

     5.继承object类,通过调用object的__new__方法创建单例对象,然后调用object的__init__方法完整初始化。

     6.双重检查加锁,既可实现线程安全,又使性能不受很大影响。

    方法二:使用decorator

    Python代码  收藏代码
    1. #encoding=utf-8  
    2. def singleton(cls):  
    3.     instances = {}  
    4.     def getInstance():  
    5.         if cls not in instances:  
    6.             instances[cls] = cls()  
    7.         return instances[cls]  
    8.     return getInstance  
    9.  
    10. @singleton  
    11. class SingletonClass:  
    12.     pass  
    13.   
    14. if __name__ == '__main__':  
    15.     s = SingletonClass()  
    16.     s2 = SingletonClass()  
    17.     print s  
    18.     print s2  

    也应该加上线程安全

    附:性能没有方法一高

    Python代码  收藏代码
    1. import threading  
    2.   
    3. class Sing(object):  
    4.     def __init__():  
    5.         "disable the __init__ method"  
    6.   
    7.     __inst = None # make it so-called private  
    8.   
    9.     __lock = threading.Lock() # used to synchronize code  
    10.  
    11.     @staticmethod  
    12.     def getInst():  
    13.         Sing.__lock.acquire()  
    14.         if not Sing.__inst:  
    15.             Sing.__inst = object.__new__(Sing)  
    16.             object.__init__(Sing.__inst)  
    17.         Sing.__lock.release()  
    18.         return Sing.__inst  
  • 相关阅读:
    应用开发笔记|MYD-YA157-V2 BSP多种方式的快速更新
    【新品发布】米尔MYC-CZU5EV新品登场,预售开启!一触即发
    价值3499元的米尔百度大脑EdgeBoard边缘AI计算盒免费试用
    Arm Development Studio 2020.1-1 Linux 64Bit下载
    Arm Development Studio 2020.1-1 Windows 64Bit下载
    应用开发笔记 | 米尔科技MYD-YA157C-V2开发板WIFI&BT 模块的移植
    Shiro简介
    Redis学习系列文章目录
    ASP.NET Core框架学习系列文章目录
    docker 基本原理
  • 原文地址:https://www.cnblogs.com/rrxc/p/4213814.html
Copyright © 2011-2022 走看看