How To Create A Singleton in Dart
第一种写法(会用一种就好)
借助dart提供的工厂构造函数,可以很方便的创建一个单例对象
class Singleton {
// 这样写就行了,别问为什么,我也不知道,慢慢理解
static final Singleton _singleton = Singleton._internal();
// Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class.
// For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype.
factory Singleton() => _singleton;
Singleton._internal(); // private constructor
}
main() {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2)); // true
print(s1 == s2); // true
}
第二种写法(如果别人这样写,能读懂代码就OK)
Another way is to use a static field that use a private constructor. This way it is not possible to create a new instance using Singleton(), the reference to the only instance is available only through the instance static field.
class Singleton {
Singleton._privateConstructor();
static final Singleton instance = Singleton._privateConstructor();
}
main() {
var s1 = Singleton.instance;
var s2 = Singleton.instance;
print(identical(s1, s2)); // true
print(s1 == s2); // true
}