我们需要比静态工厂方法更喜欢构造函数吗?如果是,什么时候? [英] Do we ever need to prefer constructors over static factory methods? If so, when?

查看:170
本文介绍了我们需要比静态工厂方法更喜欢构造函数吗?如果是,什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过 Joshua Bloch 阅读有效的Java ,到目前为止,它确实达到了它的声誉。第一个项目使静态工厂方法超过构造函数成为令人信服的情况。因此,我开始质疑好的旧构造函数的有效性:)

I have been reading Effective Java by Joshua Bloch and so far it really lives up to its reputation. The very first item makes a convincing case for static factory methods over constructors. So much that I began to question the validity of the good old constructors :).

本书的优点/缺点总结如下:

The advantages/disadvantages from the book are summarized below:


优点



  1. 我们有总实例控制(单身,性能等)

  2. 他们可以返回子类型/接口

  3. 编译器可以提供类型推断

  1. They have names!
  2. We have total instance control (Singletons, performance, etc.)
  3. They can return a subtype/interface
  4. Compiler can provide type inference

缺点:


  1. 不能将私人类作为子类。

  2. 在构造函数中,它们不会在文档中脱颖而出


第一个缺点实际上是 A Good Thing (如本书所述)。第二个,我认为只是一个小缺点,可以很容易地解决与即将到来的java版本(注释为javadoc等。)

The first disadvantage can actually be A Good Thing (as mentioned in the book). The second one, I think is just a minor disadvantage and can be resolved easily with the upcoming java releases (annotations for javadoc etc.)

它看起来像,工厂方法几乎具有构造函数的所有优点,许多更多的优点,没有真正的缺点!

It looks like, in the end factory methods have almost all the advantages of constructors, many many more advantages, and no real disadvantages !

所以,我的问题基本上分为三部分:

So, my question is basically in three parts:


  1. 默认情况下,在构造函数上始终使用静态工厂方法是个好习惯吗?


  2. 为什么面向对象语言不为工厂提供语言级支持?

注意:有两个类似的问题:何时使用构造函数,何时使用getInstance()方法(static工厂方法)?创建对象:构造函数或静态工厂方法。但是答案要么只是提供上面的列表,要么重申我已经知道的静态工厂方法的基本原理。

Note: There are two similar questions: When to use a Constructor and when to use getInstance() method (static factory methods)? and Creation of Objects: Constructors or Static Factory Methods. However the answers either just provide the above list or reiterate the rationale behind static factory methods which I am already aware of.

推荐答案

static工厂到最后还是要调用一个构造函数。您可以将大部分功能移动到静态工厂,但不能避免使用构造函数。

static factories still have to call a constructor in the end. You can move most of the functionality into the static factory, but you cannot avoid using a constructor.

另一方面,对于简单的情况,您可以只有一个构造函数具有静态工厂。

On the other hand for simple cases, you can have just a constructor without having a static factory.

构造函数是设置最终字段的唯一方法,其中IMHO优于非最终字段。

Constructors are the only way to set final fields, which IMHO are preferable to non-final fields.

你可以在子类中使用构造函数。您不能对子类使用静态工厂。

You can use constructors can in sub-classes. You cannot use static factories for a sub-class.

如果您有一个良好的依赖注入框架来构建组件的依赖关系,您可能会发现静态工厂不会添加很多。

If you have a good dependency injection framework to build dependencies of a component, you may find that static factories don't add much.

这篇关于我们需要比静态工厂方法更喜欢构造函数吗?如果是,什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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