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;
         }

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

so it's either use a static singleton property or use a factory pattern. correct?
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.
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.
Is this what you are talking about? So it is just a matter of preference? Both have the same effect?
Yes it's only a matter of preference.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.