Flutter:什么时候应该使用工厂构造函数?

标签 flutter dart

https://flutter.dev/docs/cookbook/networking/fetch-data
在上一页的最后一个“完整示例”中,

class Album {
  final int userId;
  final int id;
  final String title;

  Album({this.userId, this.id, this.title});

  factory Album.fromJson(Map<String, dynamic> json) {
    return Album(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
    );
  }
}
它是一个 Album 类,用于接收请求中收到的 JSON 字符串并在应用程序中进行处理,
构造函数除了提供普通构造函数之外,还提供了一个工厂构造函数。
关于工厂构造函数,
https://dart.dev/guides/language/language-tour#constructors
我已阅读上述页面的工厂构造函数部分。
示例中Logger类的工厂构造函数并不总是创建新实例,所以
我可以理解添加工厂关键字,
即使在此 Complete 示例的 Album 类中,是否也需要使用工厂构造函数?
在 Album 类的情况下,由于在工厂构造函数中使用了普通构造函数,
我觉得这个工厂构造函数(Album.fromJson)总是会创建一个新实例。
实际上
Future<Album> fetchAlbum() async {
  final response =
  await http.get('https://jsonplaceholder.typicode.com/albums/16');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    var temp=json.decode(response.body);
    return Album(userId:temp['userId'],id:temp['id'],title:temp['title']);
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
如您所见,即使我尝试仅使用普通构造函数,它似乎也能正常工作。
准备和使用工厂构造函数有什么好处吗?
或者在这种情况下不使用工厂构造函数有什么问题吗?
我不确定何时首先使用工厂构造函数,
有明确的定义吗?

最佳答案

在潜入之前 工厂作为flutter中的关键字,你可以看看工厂作为设计模式,要牢记全貌。
使用工厂设计模式的主要好处

That is, the Factory Method design pattern defines an interface for a class responsible for creating an object, hence deferring the instantiation to specific classes implementing this interface. This resolves the issue of creating objects directly within the class which uses them. Also, it enables compile-time flexibility via subclassing. When objects are created within the class, it is very inflexible since you cannot change the instantiation of the object independently from the class — the class is committed to a particular object. By implementing the pattern, subclasses can be written to redefine the way an object is created.


欲了解更多信息,请参阅 here
并作为 docs指的是

Use the factory keyword when implementing a constructor that doesn’t always create a new instance of its class. For example, a factory constructor might return an instance from a cache, or it might return an instance of a subtype. Another use case for factory constructors is initializing a final variable using logic that can’t be handled in the initializer list.


所以这一切都是为了向外界隐藏创建逻辑。
当然,您可以执行以下操作
return Album(userId:temp['userId'],id:temp['id'],title:temp['title']);
但是,如果您在许多不同的组件或类中这样做,那么每当您更改创建 Album 背后的逻辑时,对象,您将需要在所有地方更改它。
另一方面,使用 Album 的类他们只关心拥有一个 Object 的类(class)的 Album ,他们不关心它是如何被实例化的,所以如果你把拥有一个实例的逻辑放在类本身之外,你就会进入所谓的 意大利面代码

关于Flutter:什么时候应该使用工厂构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63628741/

相关文章:

ios - 如何在后台的另一个插件的回调中使用插件?

flutter - Flutter Dart函数作为另一个函数的参数

dart - Flutter - 重写 CupertinoTabBar 的 "build"方法

flutter - ValueListenableBuilder不重建CheckboxListTile Flutter

Flutter - 从页面修改 AppBar

android - 获取正在运行的应用程序 flutter

flutter - Flutter如何像书本一样垂直滚动屏幕

json - 在 Flutter 和 Dart 中从 JSON 解析 double 值

flutter - 如何 : rotate a selected/set image (Flutter)

json - 抛出另一个异常 : HttpException: Connection closed while receiving data, uri =