工厂构造函数标识符的飞镖优势 [英] dart advantage of a factory constructor identifier
问题描述
我一直在研究 Flutter 应用程序的 JSON 解析,但有一个关于工厂构造函数的问题,但我无法解决.我试图了解使用工厂构造函数与普通构造函数的优势.例如,我看到相当多的 JSON 解析示例创建了一个具有 JSON 构造函数的模型类,如下所示:
I've been investigating JSON parsing for my Flutter app and have a question about factory constructors that I can't resolve. I'm trying to understand the advantage of using a factory constructor versus a plain constructor. For example, I see quite a few JSON parsing examples that create a model class with a JSON constructor like this:
class Student{
String studentId;
String studentName;
int studentScores;
Student({
this.studentId,
this.studentName,
this.studentScores
});
factory Student.fromJson(Map<String, dynamic> parsedJson){
return Student(
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
);
}
}
我还看到了相同数量的示例,它们不将构造函数声明为工厂.两种类型的 classname.fromJSON 构造函数都从 JSON 数据创建一个对象,那么将构造函数声明为工厂或在这里使用工厂是多余的吗?
I've also seen an equal number of examples that DON'T declare the constructor as a factory. Both types of classname.fromJSON constructors create an object from the JSON data so is there an advantage to declaring the constructor as a factory or is using a factory here superfluous?
推荐答案
普通构造函数总是返回当前类的新实例(除非构造函数抛出异常).
A normal constructor always returns a new instance of the current class (except when the constructor throws an exception).
工厂构造函数与静态方法非常相似,区别在于它
A factory constructor is quite similar to a static method with the differences that it
- 只能返回当前类或其子类之一的实例
- 可以用
new
调用,但现在不太相关,因为new
成为可选的. - 没有初始化列表(没有
:super()
)
- can only return an instance of the current class or one of its subclasses
- can be invoked with
new
but that is now less relevant sincenew
became optional. - has no initializer list (no
: super()
)
所以可以使用工厂构造函数
So a factory constructor can be used
- 创建子类的实例(例如取决于传递的参数
- 返回缓存实例而不是新实例
- 准备计算值以将它们作为参数转发给普通构造函数,以便可以使用它们初始化最终字段.这通常用于解决在普通构造函数的初始化列表中可以完成的操作的限制(如错误处理).
在你的例子中这段代码
studentId: parsedJson['id'],
studentName : parsedJson['name'],
studentScores : parsedJson ['score']
可以移动到普通构造函数的主体中,因为不需要初始化 final
字段.
could be moved to the body of a normal constructor because no final
fields need to be initialized.
这篇关于工厂构造函数标识符的飞镖优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!