设计模式(六):单件模式

  有时候你需要系统只产生一个类的实例,比如你的手机上面所有的应用,只能共享同一份电话薄。

  python的代码很简单:


http://blog.csdn.net/insistgogo/article/details/9412863
def
Singleton( cls ): instance = {} def GetInstance(): if cls not in instance: instance[cls] = cls() return instance[cls] return GetInstance @Singleton class SingletonCls(object): """docstring for SingletonCls""" def __init__(self ): self.name = 'This is singleton.' def GetName( self ): return self.name if __name__ == '__main__': phoneNumber = SingletonCls() print phoneNumber.GetName() phoneNumber1 = SingletonCls() if phoneNumber1 == phoneNumber: print "The same instance." else: print "Not the same."
原文地址:https://www.cnblogs.com/bracken/p/3015374.html