Salma
Salma

Reputation: 1280

How to implement Singleton pattern in Dart using factory constructors?

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

Upvotes: 4

Views: 4302

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657288

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.

Upvotes: 6

Related Questions