因为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 }