Python 單例

方法一python

  實現__new__方法,而後將類的一個實例綁定到類變量_instance上;若是cls._instance爲None,則說明該類尚未被實例化過,new一個該類的實例,並返回;若是cls._instance不爲None,直接返回_instance,代碼以下spa

class Singleton(object):
  
  def __new__(cls, *args, **kwargs):
    if not hasattr(cls, '_instance'):
      orig = super(Singleton, cls)
      cls._instance = orig.__new__(cls, *args, **kwargs)
    return cls._instance
  
class MyClass(Singleton):
  a = 1
  
one = MyClass()
two = MyClass()
  
#one和two徹底相同,能夠用id(), ==, is檢測
print id(one)  # 29097904
print id(two)  # 29097904
print one == two  # True
print one is two  # True

方法二code

  本質上是方法一的升級版,使用__metaclass__(元類)的高級python用法,具體代碼以下:blog

class Singleton2(type):
  
  def __init__(cls, name, bases, dict):
    super(Singleton2, cls).__init__(name, bases, dict)
    cls._instance = None
  
  def __call__(cls, *args, **kwargs):
    if cls._instance is None:
      cls._instance = super(Singleton2, cls).__call__(*args, **kwargs)
    return cls._instance
  
class MyClass2(object):
  __metaclass__ = Singleton2
  a = 1
  
one = MyClass2()
two = MyClass2()
  
print id(one)  # 31495472
print id(two)  # 31495472
print one == two  # True
print one is two  # True

方法三it

  使用Python的裝飾器(decorator)實現單例模式,這是一種更Pythonic的方法;單利類自己的代碼不是單例的,通裝飾器使其單例化,代碼以下:class

  

def singleton(cls, *args, **kwargs):
  instances = {}
  def _singleton():
    if cls not in instances:
      instances[cls] = cls(*args, **kwargs)
    return instances[cls]
  return _singleton
  
@singleton
class MyClass3(object):
  a = 1
  
one = MyClass3()
two = MyClass3()
  
print id(one)  # 29660784
print id(two)  # 29660784
print one == two  # True
print one is two  # True
相關文章
相關標籤/搜索