您的位置:首页 > 编程语言 > Python开发

23种设计模式之python实现--单例模式

2014-04-01 21:00 585 查看
好了,今天就先实现这几个模式吧。

#理解
#世界上有一些东西是唯一的,比如地球,或者如果一个办公室只用一台打印机,那这台打印机也是唯一的
#例子:实现只有一个地球
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls, '_instance'):
old=super(Singleton,cls)
cls._instance=old.__new__(cls,*args,**kw)
return cls._instance
class Earth(Singleton):
sharp='ball'
if __name__=="__main__":
earth1=Earth()
print earth1.sharp
earth1.sharp='circle'
earth2=Earth()
print earth2.sharp
运行的结果,如图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: