Item 1: Consider static factory methods instead of constructors
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. Any subtype of the declared return type is permissible. The class of the returned object can also vary from release to release
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. This list is far from exhaustive:
Date d = Date.from(instant);
Set<Rank> faceCards = EnumSet.of(JACK, QUEEN, KING);
BigInteger prime = BigInteger.valueOf(Integer.MAX_VALUE);
StackWalker luke = StackWalker.getInstance(options);
Object newArray = Array.newInstance(classObject, arrayLen);
FileStore fs = Files.getFileStore(path);
BufferedReader br = Files.newBufferedReader(path);
List<Complaint> litany = Collections.list(legacyLitany);
结论:优先考虑静态工厂,静态工厂不合适,再考虑public constructors
Item 2: Consider a builder when faced with many constructor parameters
This client code is easy to write and, more importantly, easy to read. The Builder pattern simulates named optional parameters as found in Python and Scala.
The Builder pattern is well suited to class hierarchies.
the Builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters
Item 3: Enforce the singleton property with a private constructor or an enum type
Making a class a singleton can make it difficult to test its clients
The main advantage of the public field approach is that the API makes it clear
that the class is a singleton: the public static field is final, so it will always contain
the same object reference. The second advantage is that it’s simpler.
a single-element enum type is often the best way to implement a singleton
Item 4: Enforce noninstantiability with a private constructor
Item 5: Prefer dependency injection to hardwiring resources
Item 6: Avoid creating unnecessary objects