gpt4 book ai didi

constructor - 如何使用工厂构造函数在 Dart 中实现单例模式?

转载 作者:行者123 更新时间:2023-12-03 02:44:43 25 4
gpt4 key购买 nike

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

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()适用于构造函数每次都返回一个新实例或该类返回缓存实例的类。了解对象的实际创建方式和时间不是调用者的责任。

你可以改变

factory DbHelper(){ return _db;} 


DbHelper get singleton { return _db;}   

并使用获取实例
var mySingletonReference = DbHelper.singleton;

代替
var mySingletonReference = DbHelper();

这只是一个偏好问题。

关于constructor - 如何使用工厂构造函数在 Dart 中实现单例模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com