你如何在 Dart 中构建一个单身人士?

你如何在 Dart 中构建一个单身人士?

问题描述:

单例模式确保只创建一个类的一个实例.我如何在 Dart 中构建它?

The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?

感谢 Dart 的 工厂构造函数,很容易构建一个单例:

Thanks to Dart's factory constructors, it's easy to build a singleton:

class Singleton {
  static final Singleton _singleton = Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

你可以这样构造它

main() {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}