为什么单例模式从未显示为带有 const 构造函数的 class?

Why is the singleton pattern never shown as a class with const constructor?

这是一种模式,可确保我们只创建 class 的一个实例。

大多数时候显示单例模式:

 class Settings {
      static final Settings _instance = Settings._internal();
      factory Settings() {
        return _instance;
      }
      Settings._internal() {}
    }

缺点:难以测试,违反单一职责

怎么样:

class Singleton{
   const Singleton();
}


Singleton s1=  const Singleton();
Singleton s2=  const Singleton();

  void main() {
    print(s1==s2); //true
}

易于测试。只有一个1对象的职责。

我的问题是为什么人们让生活变得更加困难并且从不使用 const 构造函数实现 Singleton。我错过了什么吗?

除了 Christopher Moore 关于 const 的评论外,不可变单例不太可能有用,非 factory const 构造函数不保证单个实例,这将违反单例模式。调用方需要 显式 const 上下文中调用构造函数:

class Foo {
  const Foo();
}

void main() async {
  const foo1 = Foo();
  const foo2 = Foo();
  var foo3 = Foo();

  print(foo1 == foo2); // Prints: true
  print(foo1 == foo3); // Prints: false
}

相比之下,factory构造函数可以保证只创建一个实例,而不会给调用者带来额外的负担。