首页 > 其他 > 详细

dart基础---->单例singleton

时间:2020-07-23 15:29:14      阅读:78      评论:0      收藏:0      [点我收藏+]

At least, there are three ways to create the singleton object with dart.

1. factory constructor

class SingletonOne {
  SingletonOne._privateConstructor();
  static final SingletonOne _instance = SingletonOne._privateConstructor();

  factory SingletonOne() {
    return _instance;
  }
}

2. static field with getter

class SingletonTwo {
  SingletonTwo._privateConstructor();
  static final SingletonTwo _instance = SingletonTwo._privateConstructor();

  static SingletonTwo get instance => _instance;
}

3. static field

class SingletonThree {
  SingletonThree._privateConstructor();

  static final SingletonThree instance = SingletonThree._privateConstructor();
}

How to instanstiate

The above singletons are instantiated like this:

SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;

Example to test it

main(List<String> args) {
  var s1 = SingletonOne();
  var s2 = SingletonOne();
  print(identical(s1, s2)); // true
  print(s1 == s2); // true
}

dart基础---->单例singleton

原文:https://www.cnblogs.com/huhx/p/13364314.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!