我读了以下帖子:
- How do you build a Singleton in Dart?个
- How to implement Singleton pattern in Dart using factory constructors?个
- Object Structures in 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 { 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 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),工厂模式不是很有用吗?