4

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;
         }
Abdul Hoque Nuri
  • 1,105
  • 1
  • 9
  • 18
Salma
  • 1,211
  • 2
  • 16
  • 33

1 Answers1

6

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • so it's either use a static singleton property or use a factory pattern. correct? – Salma Dec 28 '18 at 09:52
  • 1
    You can also change `static final DbHelper _db = new DbHelper._constr();` to `static 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. – Günter Zöchbauer Dec 28 '18 at 09:57
  • I'm not really understanding. A full example (or a link to one) would be really helpful. I also don't understand how the use cases affect it. – Suragch Jan 05 '19 at 19:53
  • Is [this](https://stackoverflow.com/a/26044729/3681880) what you are talking about? So it is just a matter of preference? Both have the same effect? – Suragch Jan 05 '19 at 20:02
  • Yes it's only a matter of preference. – Günter Zöchbauer Jan 05 '19 at 20:53
  • I expanded my questions here: https://stackoverflow.com/questions/54057958/comparing-ways-to-create-singletons-in-dart – Suragch Jan 06 '19 at 01:47