dart基础---->单例singleton

At least, there are three ways to create the singleton object with dart.

1. factory constructor

class SingletonOne {
  SingletonOne._privateConstructor();
  static final SingletonOne _instance = SingletonOne._privateConstructor();

  factory SingletonOne() {
    return _instance;
  }
}

2. static field with getter

class SingletonTwo {
  SingletonTwo._privateConstructor();
  static final SingletonTwo _instance = SingletonTwo._privateConstructor();

  static SingletonTwo get instance => _instance;
}

3. static field

class SingletonThree {
  SingletonThree._privateConstructor();

  static final SingletonThree instance = SingletonThree._privateConstructor();
}

How to instanstiate

The above singletons are instantiated like this:

SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;

Example to test it

main(List<String> args) {
  var s1 = SingletonOne();
  var s2 = SingletonOne();
  print(identical(s1, s2)); // true
  print(s1 == s2); // true
}