Chinaunix首页 | 论坛 | 博客
  • 博客访问: 18795
  • 博文数量: 4
  • 博客积分: 170
  • 博客等级: 入伍新兵
  • 技术积分: 52
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-28 09:25
个人简介

帝都码农

文章分类

全部博文(4)

文章存档

2013年(1)

2012年(3)

我的朋友

分类: Python/Ruby

2012-12-08 18:45:24

方法一:

点击(此处)折叠或打开

  1. class Singleton(object):
  2.     __instance = None

  3.     def __init__():
  4.         '''
  5.         disable __init__
  6.         '''
  7.         pass

  8.     def initInstance(self):
  9.         pass

  10.     @staticmethod
  11.     def getInstance():
  12.         '''
  13.         this is the only access to get the instance of this class
  14.         '''
  15.         if(Singleton.__instance == None):
  16.            Singleton.__instance = object.__new__(Singleton)
  17.            Singleton.__instance.initInstance()
  18.         return Singleton.__instance

  19.     @staticmethod
  20.     def destroyInstance():
  21.         if(Singleton.__instance):
  22.             Singleton.__instance = None


  23. if(__name__ == '__main__'):
  24.     _singleton = Singleton.getInstance()
  25.     _singleton.value = 'abc'
  26.     print _singleton.value
  27.     Singleton.destroyInstance()

方法二:
还可以在创建对象时利用__new__方法判断本类是否有对象存在,如果存在就返回已经存在的对象,如果不存在就创建新的对象并返回。可以直接在一个基类中记录类和生成的对象:

点击(此处)折叠或打开

  1. class Singleton(object):
  2.     __instances = {}
  3.     def __new__(cls, *args, **kwargs):
  4.         name = '.'.join((cls.__module__, cls.__name__))
  5.         if name not in Singleton.__instances:
  6.             Singleton.__instances[name] = object.__new__(cls, *args, **kwargs)
  7.         return Singleton.__instances[name]

  8. if __name__ == "__main__":
  9.     class T(Singleton):
  10.         pass
  11.     print T() is T()

方法三:
和方法二相似,但不记录类的对象,利用gc垃圾回收机制的引用来查找对象

点击(此处)折叠或打开

  1. import gc

  2. class Singleton(object):
  3.     def __new__(cls, *args, **kwargs):
  4.         for obj in gc.get_referrers(cls):
  5.             if obj.__class__ == cls:
  6.                 return obj
  7.         return object.__new__(cls, *args, **kwargs)

  8. if __name__ == "__main__":
  9.     class T(Singleton):
  10.         pass
  11.     print T() is T()
阅读(540) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:添加Keystone扩展

给主人留下些什么吧!~~