python單例模式:python
Python真的須要單例模式嗎?我指像其餘編程語言中的單例模式。 編程
答案是:不須要! 由於,Python有模塊(module),最pythonic的單例典範。模塊在在一個應用程序中只有一份,它自己就是單例的,將你所須要的屬性和方法,直接暴露在模塊中變成模塊的全局變量和方法便可 編程語言
#!/usr/bin/env python #encoding=utf-8 import threading #單例類 class Singleton(object): instance = None mutex =threading.Lock() def __init__(self): pass @ staticmethod #聲明這個是靜態方法 def GetInstance(): if(Singleton.instance == None): Singleton.mutex.acquire() if(Singleton.instance == None): print "init the instance" Singleton.instance = Singleton() else: print "init the instance already" Singleton.mutex.release() else: print "init the instance already" return Singleton.instance if __name__ == '__main__': Singleton.GetInstance() Singleton.GetInstance() Singleton.GetInstance() #類只能調用到靜態的方法,切記