问题
I'm trying to implement the singleton pattern in a database helper class, but, I can't seem to understand the purpose of a factory constructor and if there's an alternative method to using it.
class DbHelper {
final String tblName ='';
final String clmnName ='';
final String clmnPass='';
DbHelper._constr();
static final DbHelper _db = new DbHelper._constr();
factory DbHelper(){ return _db;}
Database _mydb;
Future<Database> get mydb async{
initDb() {
if(_mydb != null)
{
return _mydb;
}
_mydb = await initDb();
return _mydb;
}
回答1:
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.
You can change
factory DbHelper(){ return _db;}
to
DbHelper get singleton { return _db;}
and acquire the instance using
var mySingletonReference = DbHelper.singleton;
instead of
var mySingletonReference = DbHelper();
It's just a matter of preference.
回答2:
I also found this article helpful: https://theburningmonk.com/2013/09/dart-implementing-the-singleton-pattern-with-factory-constructors/
来源:https://stackoverflow.com/questions/53956106/how-to-implement-singleton-pattern-in-dart-using-factory-constructors