如何使用工厂构造函数在Dart中实现Singleton模式? [英] How to implement Singleton pattern in Dart using factory constructors?

查看:91
本文介绍了如何使用工厂构造函数在Dart中实现Singleton模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在数据库帮助程序类中实现单例模式,但是,我似乎无法理解工厂构造函数的用途以及是否有替代方法来使用它。

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


推荐答案

无需使用工厂构造函数。
new 还不是可选的时,工厂构造函数很方便,因为那时 new MyClass()适用构造函数每次都返回一个新实例或该类返回一个缓存实例的类。知道实际创建对象的方式和时间不是呼叫者的责任。

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.

您可以更改

factory DbHelper(){ return _db;} 

DbHelper get singleton { return _db;}   

并使用

var mySingletonReference = DbHelper.singleton;

而不是

var mySingletonReference = DbHelper();

这只是一个偏好问题。

这篇关于如何使用工厂构造函数在Dart中实现Singleton模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆