Dart单例模式

  ⋅   :83  ⋅   :0  ⋅   Flutter

单例模式确保只有一个类的实例被创建。我如何在Dart中构建这个?

下面是两种实现方法

class MyTest{
  int nums = 0;
  static final MyTest _instance = new MyTest._init();
  factory MyTest(){
    return _instance;
  }
  MyTest._init(){
     nums++;
    print('is inited $nums');
  }
}
class MyAbc{
  int nums = 0;
  MyAbc(){
    nums++;
    print(nums);
  }
}
class MyInstance{
  int nums = 0;
  static MyInstance _instance;
  static getInstance() {
    if (_instance == null) {
      _instance = MyInstance();
    }
    return _instance;
  }
  MyInstance(){
     nums++;
    print(nums);
  }
}
void main(){
  var s1 = new MyTest();
  var s2 = new MyTest();
  print(identical(s1, s2));  // true
  print(s1 == s2); 
  var s3 = new MyAbc();
  var s4 = new MyAbc();
  print(identical(s3, s4));  // false
  var b1=MyInstance.getInstance();
  var b2=MyInstance.getInstance();
  print(identical(b1, b2));  // true
}

来源:https://stackoverflow.com/questions/12649573/how-do-you-build-a-singleton-in-dart

标签:flutter dart

如需评论,请填写表单。
换一个

记住我的信息