码迷,mamicode.com
首页 > 编程语言 > 详细

Python单例模式

时间:2015-01-09 19:09:55      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:

方法一

 

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  

Python单例模式

标签:

原文地址:http://www.cnblogs.com/rrxc/p/4213814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!