静态工厂方法与实例(普通)构造函数? [英] Static factory methods vs Instance (normal) constructors?

查看:25
本文介绍了静态工厂方法与实例(普通)构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在两者都可用的语言中,您更愿意看到实例构造函数还是返回实例的静态方法?

In a language where both are available, would you prefer to see an instance constructor or a static method that returns an instance?

例如,如果您要从 char[] 创建一个 String:

For example, if you're creating a String from a char[]:

  1. String.FromCharacters(chars);

new String(chars);

推荐答案

Effective Java, 2nd edition,Joshua Bloch 当然推荐前者.有几个原因我能记住,当然有些我不能:

In Effective Java, 2nd edition, Joshua Bloch certainly recommends the former. There are a few reasons I can remember, and doubtless some I can't:

  • 您可以为方法指定一个有意义的名称.如果您有两种构造实例的方法,这两种方法都采用 int,但对 int 有不同的含义,那么使用普通方法会使调用代码更具可读性.
  • 第一个推论 - 您可以使用具有相同参数列表的不同工厂方法
  • 您可以为潜在的预期失败"情况返回 null,而构造函数将总是返回一个值或抛出异常
  • 您可以返回声明之外的类型(例如返回派生类)
  • 您可以将其用作工厂,以可能多次返回对同一对象的引用

缺点:

  • 目前这不是惯用的 - 开发人员更习惯于看到新"
  • 如果您看到new",您就知道您正在获得一个新实例(以 我最近提到的怪事)
  • 您需要为子类提供适当的构造函数
  • 在 C# 3 中,构造函数调用能够使用对象初始值设定项表达式以紧凑的方式设置字段/属性;该功能不适用于静态方法调用
  • It's not as idiomatic, currently - developers are more used to seeing "new"
  • If you see "new" you know you're getting a new instance (modulo the oddity I mentioned recently)
  • You need to make appropriate constructors available for subclasses
  • In C# 3, constructor calls are able to set fields/properties in a compact manner with object initializer expressions; the feature doesn't apply to static method calls

这篇关于静态工厂方法与实例(普通)构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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