How do you build a Singleton in Dart?

2020-01-24 03:19发布

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

14条回答
仙女界的扛把子
2楼-- · 2020-01-24 04:11

This should work.

class GlobalStore {
    static GlobalStore _instance;
    static GlobalStore get instance {
       if(_instance == null)
           _instance = new GlobalStore()._();
       return _instance;
    }

    _(){

    }
    factory GlobalStore()=> instance;


}
查看更多
做个烂人
3楼-- · 2020-01-24 04:12

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();
}

You can construct it like this

main() {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}
查看更多
登录 后发表回答