一、单例模式
单例模式是应用开发过程中最简单同时也是最著名的一种创建型设计模式。单例模式提供了一个类只有一个特定类型的对象的机制。
通常应用于场景为:日志记录、数据库操作等,程序运行时只能生成一个实例,避免对同一资源产生冲突的访问请求。
二、如何设计单例模式
(1)重写构造函数__new__方法
class Singleton(object):
def __new__(self):
if not hasattr(self,'instance'):
self.instance = super(Singleton,self).__new__(self)
return self.instance
a = Singleton()
b = Singleton()
print id(a),id(a)
该方法主要思路就是在覆盖实例化函数__new__(),在其中添加判断,检查对象是否存在。hasattr是python的特殊方法,用来查看对象是否具有某个属性。
当然,如果想要继承这个Singleton,子类中一定不要忘了重写__new__方法,否则会覆盖掉父类中已经修改的方法。
class Singleton(object):
def __new__(self):
if not hasattr(self,'instance'):
self.instance = super(Singleton,self).__new__(self)
return self.instance
class test(Singleton):
def __new__(self):<