【问题标题】:Why use the factory constructor in this case为什么在这种情况下使用工厂构造函数
【发布时间】:2019-05-15 02:48:38
【问题描述】:

我在this article 中发现了一个有用的解析复杂 JSON 工具。 The tool 将采用 JSON 示例并以您选择的编程语言对其进行解析。

我目前正在使用 Dart 以及我的简单原始 JSON“内容”示例:

{
  "title": "Welcome to quicktype!"
}

被这个 JSON tool in Dart 解析创建这个 Dart 类:

import 'dart:convert';

Content contentFromJson(String str) => Content.fromJson(json.decode(str));

String contentToJson(Content data) => json.encode(data.toJson());

class Content {
    String title;

    Content({
        this.title,
    });

    factory Content.fromJson(Map<String, dynamic> json) => new Content(
        title: json["title"],
    );

    Map<String, dynamic> toJson() => {
        "title": title,
    };
}

在这种情况下,工厂构造函数的目的是什么?没有存储 Content 类实例的“私有”变量。没有检查缓存或键,以便在使用相同原始 JSON 数据参数的后续 Content.fromJson 调用中返回已实例化的 Content 类。

因为使用了 factory 关键字,这是否意味着 Dart 仅仅因为该方法被表示为工厂构造函数,就在后台处理重用相同的实例化?

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    我认为在该示例中不需要使用 factory。它可能是一个普通的命名构造函数:

    Content.fromJson(Map<String, dynamic> json) : this(title: json["title"]);
    

    也就是说,即使没有必要,factory 也有一些有用的原因:

    • 它可能会在某天返回一个现有实例而不是保证一个新实例。

    • 如果将任何错误检查代码添加到 Content.fromJson,它可能需要构造函数主体,并且可能不再能够委托给主构造函数。 factory 构造函数不使用初始化列表,因此没有这个限制。

    当然,在这种情况下,factory 构造函数也是不必要的,因为它也可以是 static 方法 (which could provide other benefits)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2018-12-06
      相关资源
      最近更新 更多