gpt4 book ai didi

java - 创建对象 : Constructors or Static Factory Methods

转载 作者:太空狗 更新时间:2023-10-29 22:34:02 26 4
gpt4 key购买 nike

我正在学习 Effective Java 并且书中没有建议我认为是标准的一些东西,例如对象的创建,我的印象是构造函数是最好的方法这样做的书上说我们应该使用静态工厂方法,我不能说出一些优点和缺点,所以我问这个问题,这里是使用它的好处。

Advantages:

  1. One advantage of static factory methods is that, unlike constructors, they have names.
  2. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
  3. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
  4. A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

Disadvantages:

  1. The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
  2. A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

Reference: Effective Java, Joshua Bloch, Edition 2, pg: 5-10

我无法理解第四个优点和第二个缺点,如果有人能解释这些要点,我将不胜感激。我还想了解如何决定是使用构造函数还是静态工厂方法来创建对象。

最佳答案

  • 优点四:使用构造函数时,你有

    Foo<Map<Key, Value>> foo = new Foo<Map<Key, Value>>();

    对比

    Foo<Map<Key, Value>> foo = Foo.createFoo(); // no need to repeat

    这个优势在 Java 7 中将不复存在,届时将引入菱形语法

  • 缺点 2. 您无法轻易判断给定的 static 方法是用于构造函数还是用于其他用途。

至于如何选择 - 没有单一的方法。您可以权衡上述所有给定用例的优缺点,但大多数情况下,这只是根据经验做出的决定。

关于java - 创建对象 : Constructors or Static Factory Methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4617311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com