How to implement Singleton pattern in Dart using factory constructors?

荒凉一梦 提交于 2020-01-01 19:14:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!