《python单例模式实例分析》由会员分享,可在线阅读,更多相关《python单例模式实例分析(3页珍藏版)》请在金锄头文库上搜索。
1、我真正系统地接触和学习党的基本知识是在这次中级党校的培训班上。通过学习,了解了党的发展历程,对党的性质、宗旨、任务等基本知识有了进一步的了解Python单例模式实例分析本文实例讲述了Python单例模式的使用方法。分享给大家供大家参考。具体如下:方法一复制代码 代码如下:import threadingclass Singleton(object):_instance = None_lock = threading.Lock() # used to synchronize codedef _init_(self):disable the _init_ methodstaticmethoddef
2、 getInstance():if not Singleton._instance:Singleton._lock.acquire()if not Singleton._instance:Singleton._instance = object._new_(Singleton)object._init_(Singleton._instance)Singleton._lock.release()return Singleton._instance1.禁用_init_方法,不能直接创建对象。2._instance,单例对象私有化。静态方法,通过类名直接调用。4._lock,代码锁。5.继承obje
3、ct类,通过调用object的_new_方法创建单例对象,然后调用object的_init_方法完整初始化。6.双重检查加锁,既可实现线程安全,又使性能不受很大影响。方法二:使用decorator复制代码 代码如下:#encoding=utf-8def singleton(cls):instances = def getInstance():if cls not in instances:instancescls = cls()return instancesclsreturn getInstancesingletonclass SingletonClass:passif _name_ = _
4、main_:s = SingletonClass()s2 = SingletonClass()print sprint s2也应该加上线程安全复制代码 代码如下:import threadingclass Sing(object):def _init_():disable the _init_ method_inst = None # make it so-called private_lock = threading.Lock() # used to synchronize codestaticmethoddef getInst():Sing._lock.acquire()if not Sing._inst:Sing._inst = object._new_(Sing)object._init_(Sing._inst)Sing._lock.release()return Sing._inst希望本文所述对大家的Python程序设计有所帮助。对党的认识也有了进一步的提高。才真正体会到了中国共产党的伟大、光荣和正确,更感到只有中国共产党是全中国最广大人民利益的忠实代表