特点:确保某一个类只有一个实例对象
模块
python的模块就是一个天然的单例模式。当模块第一次导入时会产生一个.pyc文件,当第二次用时,直接加载.pyc文件,不会再次执行该模块的代码。装饰器
def SingleTon(cls, *args, **kwargs):
_instance = {}
def singleton():
if cls not in _instance:
_instance[cls] = cls(*args, **kwargs)
return _instance[cls]
return singleton
@SingleTon
class A(object):
a = 1
t1 = A()
print(id(t1)) # 915018585536
t2 = A()
print(id(t2)) # 915018585536
- 类(基于__new__)
class SingleTon(object):
_isinstance = None
def __new__(cls, *args, **kwargs):
if not cls._isinstance:
cls._isinstance = super(SingleTon, cls).__new__(cls, *args, **kwargs)
return cls._isinstance
t1 = SingleTon()
print(id(t1)) # 744789979936
t2 = SingleTon()
print(id(t2)) # 744789979936