Python單例模式實例分析
更新時間:2015年01月14日 10:21:22 投稿:shichen2014
這篇文章主要介紹了Python單例模式,以實例形式分析了Python單例模式的具體使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python單例模式的使用方法。分享給大家供大家參考。具體如下:
方法一
復制代碼 代碼如下:
import threading
class Singleton(object):
__instance = None
__lock = threading.Lock() # used to synchronize code
def __init__(self):
"disable the __init__ method"
@staticmethod
def 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.__instance
class Singleton(object):
__instance = None
__lock = threading.Lock() # used to synchronize code
def __init__(self):
"disable the __init__ method"
@staticmethod
def 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.__instance
1.禁用__init__方法,不能直接創(chuàng)建對象。
2.__instance,單例對象私有化。
3.@staticmethod,靜態(tài)方法,通過類名直接調(diào)用。
4.__lock,代碼鎖。
5.繼承object類,通過調(diào)用object的__new__方法創(chuàng)建單例對象,然后調(diào)用object的__init__方法完整初始化。
6.雙重檢查加鎖,既可實現(xiàn)線程安全,又使性能不受很大影響。
方法二:使用decorator
復制代碼 代碼如下:
#encoding=utf-8
def singleton(cls):
instances = {}
def getInstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getInstance
@singleton
class SingletonClass:
pass
if __name__ == '__main__':
s = SingletonClass()
s2 = SingletonClass()
print s
print s2
def singleton(cls):
instances = {}
def getInstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getInstance
@singleton
class SingletonClass:
pass
if __name__ == '__main__':
s = SingletonClass()
s2 = SingletonClass()
print s
print s2
也應該加上線程安全
復制代碼 代碼如下:
import threading
class Sing(object):
def __init__():
"disable the __init__ method"
__inst = None # make it so-called private
__lock = threading.Lock() # used to synchronize code
@staticmethod
def getInst():
Sing.__lock.acquire()
if not Sing.__inst:
Sing.__inst = object.__new__(Sing)
object.__init__(Sing.__inst)
Sing.__lock.release()
return Sing.__inst
class Sing(object):
def __init__():
"disable the __init__ method"
__inst = None # make it so-called private
__lock = threading.Lock() # used to synchronize code
@staticmethod
def getInst():
Sing.__lock.acquire()
if not Sing.__inst:
Sing.__inst = object.__new__(Sing)
object.__init__(Sing.__inst)
Sing.__lock.release()
return Sing.__inst
希望本文所述對大家的Python程序設計有所幫助。
相關文章
Python保留數(shù)據(jù)并刪除Excel單元格的函數(shù)和公式
在分析處理Excel表格時,我們可能需要使用各種公式或函數(shù)對表格數(shù)據(jù)進行計算,從而分析出更多的信息,但在展示、分享或再利用分析結果時,我們可能需要將含有公式的單元格轉(zhuǎn)換為靜態(tài)數(shù)值,本文將介紹如何使用Python代碼批量移除Excel單元格中的公式并保留數(shù)值2024-10-10
Python簡單實現(xiàn)兩個任意字符串乘積的方法示例
這篇文章主要介紹了Python簡單實現(xiàn)兩個任意字符串乘積的方法,結合實例形式分析了Python針對字符串、列表的切片、轉(zhuǎn)換、遍歷等相關操作技巧,需要的朋友可以參考下2018-04-04

