从地图结构构造新实例时,为什么要使用工厂? [英] Why use factory when constructing a new instance from a map structure?

查看:39
本文介绍了从地图结构构造新实例时,为什么要使用工厂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图真正理解来自API的JSON数据流,直到可以将其用作对象为止.

I'm trying to really understand the flow of JSON data coming from an API until I can consume it as an object.

现在我想我已经准备好了一切,我唯一的问题是为什么我看到有些人在使用命名构造函数.fromJson时使用工厂.根据Dart文档:

Now I think I have everything in place, my only question is why I see some people use the factory when they use the named constructor .fromJson. According to the Dart documentation:

当我们实现一个构造函数时,我们使用factory关键字并不总是创建类的新实例.

we use the factory keyword when we implement a constructor that doesn't always create a new instance of your class.

但是在这种情况下,当使用fromJson时,我们总是会创建一个实例,对吧?

But in this case, we always will make an instance when using fromJson, right?

那为什么有人使用:

   factory User.fromJson(Map<String, dynamic> json) =>
      User(name: json['name'], alias: json['alias']);

而不是更合理的:

  User.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        alias = json['alias'];

非常感谢您的声明.

推荐答案

使公用构造函数成为工厂可能是防御性设计,即使在技术上并非必需.

Making a public constructor a factory can be a defensive design, even when it's not technically required.

如果您使生成器成为生成器,那么某个地方的某人可能会通过子类扩展您的类,并将其构造器转发给您的生成器.

If you make a constructor generative, then someone, somewhere, might extend your class with a subclass and forward their constructor to your generative constructor.

到那时,将您的构造函数变成工厂变成了重大更改.如果您决定要进行更多验证,而如果构造函数是工厂的话,它将变得更加方便,那么现在您将无法进行更改.

At that point, it becomes a breaking change to make your constructor into a factory. If you decide you want more validation and it becomes more convenient if the constructor was a factory, you're now blocked from making the change.

使公共构造函数生成是一个承诺(因此使其成为 const ),因此最好不要这样做,除非您实际上想要至.不要偶然或仅仅因为可以就公开公共生成(或const)构造函数.如果您打算通过该构造函数将该类用作超类,请执行此操作.否则,只公开工厂构造函数并使生成的构造函数保持私有是更安全的.

Making a public constructor generative is a promise (so is making it const), so you're better of not doing it unless you actually want to. Don't expose public generative (or const) constructors by accident, or just because you can. Do it if you intend the class to be used as a super-class through that constructor. Otherwise it's safer to expose only a factory constructor, and keep the generative constructor private.

这篇关于从地图结构构造新实例时,为什么要使用工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆