【发布时间】:2020-04-17 10:04:00
【问题描述】:
我的问题是关于在处理相对复杂的不可变对象时如何正确使用工厂构造函数。假设我想返回一个更改了某些属性的类的实例。
示例
@immutable
class SomeObject {
final int id;
final String name;
final int upvote;
final int downvote;
final int favorite;
SomeObject({this.id, this.name, this.upvote, this.downvote, this.favorite});
factory SomeObject.upvoted() {
return SomeObject(
upvote: this.upvote + 1 // apparently can't use this keyword here, wrong syntax
);
}
SomeObject.upvoted(SomeObject ref) {
id = ref.id;
// cant change an immutable type
}
SomeObject upvoted() {
return SomeObject(
upvote: upvote + 1,
//... other properties are null, bad idea?
);
}
SomeObject upvotedWithDefaultConstructorUsingReference(SomeObject ref) {
// works but seems like an overkill, especially considering more number of properties
return SomeObject(
id: ref.id,
name: ref.name,
upvote: upvote + 1,
downvote: ref.downvote,
favorite: ref.downvote
);
}
}
SomeObject.upvoted() 将是同一类的一个实例,但它的 upvoted 属性比引用的属性多 +1。还会有更多类似 downvoted()、withNameChanged() 或 copyWith()。
前 2 个是构造函数,其他只是返回 SomeObject 类实例的方法。这里应该采用什么方法?当类不可变时如何使用工厂构造函数?我也不确定这 4 个例子的区别。
我已经阅读了this 问题的答案,但它似乎没有回答我的问题。
【问题讨论】:
标签: oop flutter dart constructor