Python 单例模式
In [4]:
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class MyClass(object):
pass
In [6]:
single1 = Singleton()
single2 = Singleton()
myclass1 = MyClass()
myclass2 = MyClass()
print id(single1) == id(single2)
print id(myclass1) == id(myclass2)
In [7]:
from functools import wraps
def singleton(cls):
instances = {}
@wraps(cls)
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class MyClass(object):
pass
In [8]:
myclass1 = MyClass()
myclass2 = MyClass()
print id(myclass1) == id(myclass2)
In [11]:
class MySingleton(object):
@classmethod
def getInstance(cls):
if not hasattr(cls, '_instance'):
cls._instance = cls()
return cls._instance
mysingleton1 = MySingleton.getInstance()
mysingleton2 = MySingleton.getInstance()
print id(mysingleton1) == id(mysingleton2)