I read these posts:
- How do you build a Singleton in Dart?
- How to implement Singleton pattern in Dart using factory constructors?
- Object Structures in Dart
I'm having a little trouble understanding the difference between the following ways of creating singletons:
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;
Questions
Günter Zöchbauer said about this question:
There is no need to use the factory constructor. The factory constructor was convenient when new was not yet optional because then it
new MyClass()
worked for classes where the constructor returned a new instance every time or where the class returned a cached instance. It was not the callers responsibility to know how and when the object was actually created.
I don't understand how new
being optional now makes the factory constructor unnecessary now. Before you couldn't do something like SingletonTwo
or SingletonThree
above?
You can also change
static final DbHelper _db = new DbHelper._constr();
tostatic final DbHelper singleton = new DbHelper._constr();
and remove the singleton getter I suggested in my answer. It depends on your use case. You might not be able to use a field initializer if you need additional config values to create the instance. In your example it would be sufficient though.
What are the use cases for each of the singleton patterns above (SingletonOne, SingletonTwo, and SingletonThree)? It would be helpful to see an example for each. Wouldn't the factory pattern be useful if you wanted to hide the fact that the class was a singleton (as described here)?