Dart 单例的四种写法
来源:blog.csdn.net 更新时间:2023-05-25 21:55
dart中的单例
工厂构造 Factory constructor
class Singleton{
Singleton._privateConstructor();
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工厂构造函数 下一篇:flutter插件 getwidget