Effective Java 的笔记,代码、英语原文为主,批注、翻译为辅。
Item 1: Consider static factory methods instead of constructors
考虑以静态工厂方法代替构造函数
obtain an instance of the class
获得类实例的方法
provide a public constructor
provide a public static factory method
|
|
Java source code
The EnumSet class has no public constructors, only static factories.
In the OpenJDK implementation, they return an instance of one of two subclasses, depending on the size of the underlying enum type: if it hassixty-four or fewer
elements, as most enum types do, the static factories return aRegularEnumSet instance
, which is backed by asingle long
; if the enum type hassixty-five or more
elements, the factories return aJumboEnumSet instance
, backed by along array
.
EnumSet
|
|
RegularEnumSet
|
|
JumboEnumSet
|
|
Here are some common names for static factory methods. This list is far from exhaustive:
- from—A type-conversion method that takes a single parameter and returns a corresponding instance of this type, for example:
1
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:
1
Set<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING);
- valueOf—A more verbose alternative to from and of, for example:
1
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:
1
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:
1
Object newArray = Array.newInstance(classObject, arrayLen);
- getType—Like getInstance, but used if the factory method is in a different class. Type is the type of object returned by the factory method, for example:
1
FileStore fs = Files.getFileStore(path);
- newType—Like newInstance, but used if the factory method is in a different class. Type is the type of object returned by the factory method, for example:
1
BufferedReader br = Files.newBufferedReader(path);
- type—A concise alternative to getType and newType, for example:
1
List<Complaint> litany = Collections.list(legacyLitany);
summary
Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.