如何在Dart中构建一个Singleton? [英] How do you build a Singleton in Dart?
本文介绍了如何在Dart中构建一个Singleton?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
单例模式确保只有一个类的实例被创建。
The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?
推荐答案
感谢Dart的工厂构造函数,很容易构建单例:
Thanks to Dart's factory constructors, it's easy to build a singleton:
class Singleton {
static final Singleton _singleton = new Singleton._internal();
factory Singleton() {
return _singleton;
}
Singleton._internal();
}
您可以使用 new
main() {
var s1 = new Singleton();
var s2 = new Singleton();
print(identical(s1, s2)); // true
print(s1 == s2); // true
}
这篇关于如何在Dart中构建一个Singleton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文