Dart 单例的四种写法

来源:blog.csdn.net 时间:2020-10-10 21:36

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