Python 5种方法实现单例模式
基本介绍
一个对象只允许被一次创建,一个类只能创建一个对象,并且提供一个全局访问点。
单例模式应该是应用最广泛,实现最简单的一种创建型模式。
特点:全局唯一,允许更改
优缺点
优点:
避免对资源的多重占用,如写入文件操作
节省内存
防止命名空间被污染
缺点:
没有接口,不能继承,与单一职责原则冲突,一个类应该只关心内部逻辑,而不关心外面怎么样来实例化
Python实现
方式1,元类实现:
class MetaClass(type):
def __call__(self, *args, **kwargs):
"""
self : class Singleton
"""
if not hasattr(self, "ins"):
insObject = super(__class__, self).__call__(*args, **kwargs)
setattr(self, "ins", insObject)
return getattr(self, "ins")
class Singleton(object, metaclass=MetaClass):
pass
if __name__ == "__main__":
ins = Singleton()
print(id(ins))
ins = Singleton()
print(id(ins))
方式2,继承实现:
class ParentClass:
def __new__(cls, *args, **kwargs) -> object:
"""
cls : class Singeton
"""
if not hasattr(cls, "ins"):
insObject = super(__class__, cls).__new__(cls, *args, **kwargs)
setattr(cls, "ins", insObject)
return getattr(cls, "ins")
class Singleton(ParentClass):
pass
if __name__ == "__main__":
ins = Singleton()
print(id(ins))
ins = Singleton()
print(id(ins))
方式3,装饰器实现:
def warpper(clsObject):
def inner(*args, **kwargs):
if not hasattr(clsObject, "ins"):
insObject = clsObject(*args, **kwargs)
setattr(clsObject, "ins", insObject)
return getattr(clsObject, "ins")
return inner
@warpper
class Singleton:
pass
if __name__ == "__main__":
ins = Singleton()
print(id(ins))
ins = Singleton()
print(id(ins))
方式4,模块实现:
- foo.py --> ins = Singleton()
- bar.py --> from foo import ins
方式5,@classmethod实现单例模式:
class Singleton:
@classmethod
def getSingletonInstanceObject(cls, *args, **kwargs):
if not hasattr(cls, "ins"):
insObject = cls(*args, **kwargs)
setattr(cls, "ins", insObject)
return getattr(cls, "ins")
if __name__ == "__main__":
ins = Singleton.getSingletonInstanceObject()
print(id(ins))
ins = Singleton.getSingletonInstanceObject()
print(id(ins))