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() #类只能调用到静态的方法,切记