【发布时间】:2019-06-01 03:33:14
【问题描述】:
我读过这些帖子:
- How do you build a Singleton in Dart?
- How to implement Singleton pattern in Dart using factory constructors?
- Object Structures in Dart
我很难理解以下创建单例的方式之间的区别:
1.工厂构造函数
class SingletonOne {
SingletonOne._privateConstructor();
static final SingletonOne _instance = SingletonOne._privateConstructor();
factory SingletonOne(){
return _instance;
}
}
2。带 getter 的静态字段
class SingletonTwo {
SingletonTwo._privateConstructor();
static final SingletonTwo _instance = SingletonTwo._privateConstructor();
static SingletonTwo get instance { return _instance;}
}
3.静态字段
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
这些实例化如下:
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
问题
Günter Zöchbauer said 关于this question:
不需要使用工厂构造函数。工厂 当 new 还不是可选的时候,构造函数很方便,因为那时 它
new MyClass()适用于构造函数返回的类 每次或类返回缓存实例的新实例。 知道对象的方式和时间不是调用者的责任 实际上是创建的。
我不明白 new 现在是可选的如何使得工厂构造函数现在变得不必要了。在您无法执行上述SingletonTwo 或SingletonThree 之类的操作之前?
您还可以将
static final DbHelper _db = new DbHelper._constr();更改为static final DbHelper singleton = new DbHelper._constr();并删除我在我的 回答。这取决于您的用例。您可能无法使用 如果您需要其他配置值来创建字段初始值设定项 实例。不过,在您的示例中就足够了。
上述每个单例模式(SingletonOne、SingletonTwo 和 SingletonThree)的用例是什么?查看每个示例会很有帮助。如果您想隐藏类是单例的事实(如here 所述),工厂模式不是很有用吗?
【问题讨论】:
-
都是一样的。只使用你最喜欢的。