当前位置: 代码迷 >> 综合 >> Dart 单例的四种写法
  详细解决方案

Dart 单例的四种写法

热度:32   发布时间:2023-12-10 22:04:29.0

Dart汇总请点击这里

文章目录

      • dart中的单例
        • 工厂构造 Factory constructor
        • 静态变量 Static field with getter
        • 静态变量Static field
        • 常量和工厂构造 const constructor & factory

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()));
}