gpt4 book ai didi

java - 何时使用构造函数以及何时使用 getInstance() 方法(静态工厂方法)?

转载 作者:IT老高 更新时间:2023-10-28 11:44:48 26 4
gpt4 key购买 nike

  1. 我们应该何时以及如何使用构造函数

    Foo bar = new Foo();
  2. 以及我们应该何时以及如何使用 getInstance()(静态工厂方法)

    Foo bar = Foo.getInstance();

这两者有什么区别?我一直使用构造函数,但是什么时候应该使用 getInstance() 代替?

最佳答案

似乎每个人都关注单例,而我认为问题实际上是关于 构造函数与静态工厂方法

这实际上是 Effective Java第 1 项:考虑静态工厂方法而不是构造函数约书亚布洛赫:

Item 1: Consider static factory methods instead of constructors

The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here’s a simple example from Boolean (the boxed primitive class for the primitive type boolean). This method translates a boolean primitive value into a Boolean object reference:

public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}

Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95, p. 107]. The static factory method described in this item has no direct equivalent in Design Patterns.

A class can provide its clients with static factory methods instead of, or in addition to, constructors. Providing a static factory method instead of a public constructor has both advantages and disadvantages.

优点(引用本书):

  • 静态工厂方法的一个优点是,与构造函数不同,它们有名称。
  • 静态工厂方法的第二个优点是,与构造函数不同,它们不需要在每次调用时都创建一个新对象。
  • 静态工厂方法的第三个优点是,与构造函数不同,它们可以返回其返回类型的任何子类型的对象。
  • 静态工厂方法的第四个优点是它们减少了创建参数化类型实例的冗长性。

缺点(还是引用书):

  • 只提供静态工厂方法的主要缺点是没有公共(public)或 protected 构造函数的类不能被子类化。
  • 静态工厂方法的第二个缺点是它们不是很容易与其他静态方法区分开来。

关于java - 何时使用构造函数以及何时使用 getInstance() 方法(静态工厂方法)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3169372/

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