使用__new__实现单例模式

单例模式是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在,节约内存资源。

class Singleton():
    def __new__(cls):
        if not hasattr(cls, "_instance"):
            cls._instance = super().__new__(cls)
        return cls._instance


a = Singleton()
b = Singleton()
print(id(a))
print(id(b))
# id(a) == id(b)

每次实例化一个对象时,都会先调用 _new_() 函数创建一个对象,再调用 _init_() 函数初始化数据。因而,在 new函数中判断 Singleton类 是否已经实例化过,如果不是,调用父类的 new 函数创建实例;否则返回之前创建的实例。
_instance 作为类属性,保证了所有对象的 _instance 都是同一个。

应用场景

  • 网站的计数器
  • 应用配置
  • 日志应用
  • 线程池
  • 数据库连接池

猜你喜欢

转载自blog.csdn.net/weixin_44857400/article/details/107361411