如何用Dart寫一個單例

因爲Dart擁有factory constructors,所以構建單例模式很容易。ide

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

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

咱們可使用new來構造代碼以下:ui

main() {
  var s1 = new Singleton();
  var s2 = new Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}
相關文章
相關標籤/搜索