问题描述
-
我们何时以及如何使用构造函数
When and how should we use a Constructor
Foo bar = new Foo();
我们何时以及如何使用getInstance()(静态工厂方法)
And When and how should we use getInstance() (static factory methods)
Foo bar = Foo.getInstance();
这两者有什么区别,我总是使用第一种方式,但何时使用第二种方式?
What is the difference between these two, I always use the 1st way but when to use the 2nd way?
推荐答案
每个人似乎都专注于单身,而我认为这个问题实际上是关于构造函数与静态工厂方法。
Everybody seems to focus on singletons while I think that the question is actually about constructor vs static factory methods.
这实际上是第1项:考虑静态工厂方法而不是:
This is actually Item 1: Consider static factory methods instead of constructors of Effective Java by Joshua Bloch:
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
请注意,静态工厂方法是
与b $ b不同来自设计模式的工厂方法
模式
[Gamma95,p。 107]。此项目中描述的静态工厂
方法在 Design
Patterns 中没有
直接等价物。
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.
优点(引用本书):
- 静态工厂方法的一个优点是,与构造函数不同,它们具有名称。
- 静态工厂方法的第二个优点是,与构造函数不同,它们不需要在每次调用时创建新对象。
- 静态工厂方法的第三个优点是,与构造函数不同,它们可以返回其返回类型的任何子类型的对象。
- 静态工厂方法的第四个优点是它们减少了创建参数化类型实例的详细程度。
- One advantage of static factory methods is that, unlike constructors, they have names.
- 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.
- A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
- A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.
缺点(仍在引用本书):
Disadvantages (still quoting the book):
- 仅提供静态工厂方法的主要缺点是没有公共或受保护构造函数的
类不能被子类化。 - 静态工厂方法的第二个缺点是它们不是很容易与其他静态方法区分的
。
这篇关于何时使用构造函数以及何时使用getInstance()方法(静态工厂方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!