Cbdy
2018-09-27 19:08:13 +08:00
Effective Java 第三版第二章第一节有详细介绍
我简单摘录一下:
### 优点
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 factories is that the class of the returned object can vary from call to call as a function of the input parameters.
A fifth advantage of static factories is that the class of the returned object need not exist when the class containing the method is written.
### 缺点
The main limitation of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
A second shortcoming of static factory methods is that they are hard for programmers to find.
### 一些常见的静态构造方法
**from**: A type-conversion method that takes a single parameter and returns a corresponding instance of this type, for example:
```java
Date d = Date.from(instant);
```
**of**: An aggregation method that takes multiple parameters and returns an instance of this type that incorporates them, for example:
```java
Set<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING);
```
**valueOf**: A more verbose alternative to from and of, for example:
```java
BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE);
```
**instance** or **getInstance**: Returns an instance that is described by its parameters (if any) but cannot be said to have the same value, for example:
StackWalker luke = StackWalker.getInstance(options);
**create** or **newInstance**: Like instance or getInstance, except that the method guarantees that each call returns a new instance, for example:
```java
Object newArray = Array.newInstance(classObject, arrayLen);
```