本文主要是介绍Dart 单例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
工厂构造 Factory constructor
class Singleton{Singleton._privateConstructor(){//todo 私有构造方法}static final Singleton _instance = Singleton._privateConstructor();factory Singleton(){return _instance;}}void main() {Singleton s = Singleton();
}
静态变量 Static field with getter
class Singleton{Singleton._privateConstructor(){}static final Singleton _instance = Singleton._privateConstructor();static Singleton get instance { return _instance;}}void main() {Singleton s = Singleton.instance;
}
静态变量Static field
class Singleton {Singleton._privateConstructor();static final Singleton instance = Singleton._privateConstructor();}void main() {Singleton s = Singleton.instance;
}
常量和工厂构造 const constructor & factory
class Singleton {factory Singleton() => const Singleton._internal_();const Singleton._internal_();
}void main() {print(new Singleton() == new Singleton());print(identical(new Singleton() , new Singleton()));
}
这篇关于Dart 单例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!