我读了以下帖子:

我在理解以下创建单身对象的方式之间的区别时遇到了一些困难:

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 { return _instance;}

}

3. Static field

class SingletonThree {

  SingletonThree._privateConstructor();

  static final SingletonThree instance = SingletonThree._privateConstructor();

}

These are instantiated like this:

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

问题

Günter Zöchbauer saidthis question:

不需要使用工厂构造函数.工厂 构造函数在new还不是可选的时候很方便,因为 它new MyClass()适用于构造函数返回 每次或类返回缓存实例时的新实例. 知道对象的方式和时间不是调用者的责任 实际上是被创造出来的.

我不明白为什么现在new是可选的,所以现在不需要工厂构造函数.在你做不到像上面的SingletonTwoSingletonThree这样的事情之前?

Günter Zöchbauer also said:

您还可以将static final DbHelper _db = new DbHelper._constr();改为static final DbHelper singleton = new DbHelper._constr();,并删除我在

上面的每个单例模式(SingletonOne、SingletonTwo和SingletonThree)的用例是什么?每种情况下都能看到一个例子会很有帮助.如果您想要隐藏类是单例的事实(如上所述here),工厂模式不是很有用吗?

推荐答案

作为Günter Zöchbauer stated in the comments,您列出的创建单例的三种方法中的每一种都是相同的.用你的个人喜好来 Select 一个.

我将添加一些附加说明:

  • SingletonOne在实例化时看起来与任何其他类一样.因此,如果您想要隐藏它是单例的事实(并保留将来使其不是单例的选项),则可以使用此方法.您还可以在构造函数中传入参数.
  • SingletonTwo将允许您在返回实例之前执行其他工作.
  • SingletonThree是最短的,在我看来,在其他条件相同的情况下,短而干净的代码是可取的.

Dart相关问答推荐

从GTIN中提取GS1公司前缀

dart run edge build cloudflare_workers --dev 命令在我的项目(笔记本电脑)中不起作用

如何防止 getter 或函数每次都重新计算?

VS Code 无法识别 Flutter 中的单元测试

Flutter/Dart:子类化冻结的数据类

如何在streambuilder中查询firestore文档并更新listview

Dart 中使用 ifAbsent 的 Map Update 方法

如何在Flatter中设置特定容器中所有文本的 colored颜色 ?

有没有更好的方法来解析 Dart 中的 int

如何使用 Dart 动态加载 HTML 并插入我的网页?

如何在dart中的多个文件中编写多个单元测试?

设置Dart中非常量的默认值

找到两个数字中larger/smaller的方法是什么

dart 是否支持运算符重载

在 Dart 中,将动态转换为给定类型或返回 null 的语法好方法?

如何以 Dart 语言将变量完全转储/打印到控制台?

如何使异步 Dart 调用同步?

在 DART 中创建泛型类型的实例

判断dart中的字符串是否为数字

如何比较 Dart 中的列表是否相等?