Effective Java(1)
Item1: consider static factory methods instead of constructors
advantages:
-
They have names
-
They not required to create a new object each time they are invoked
-
They can return an object of any subtype of their return type
-
The class of the returned object can vary from call to call as a function of the input parameters
-
The class of the returned object need not exist when the class containing the method is written
shortcomming:
-
Classes without public or protected constructors cannot be subclassed
-
Hard for programmers to find
sum-up: first consider static factories before providing public constructors
Item 2: consider a builder when faced with many constructor parameters
The builder›s setter methods return the builder itself(return this) so that invocations can be chained, resulting in a fluent API
when-to-use: when you have more than a handful of optional parameters
Item 3: enforce the singleton property with a private constructor or an enum type
Item 4 : enforce noninstantiability with a private constructor
Item 5: prefer dependency injection to hardwiring resources
Item 6: avoid creating unnecessary objects
浙公网安备 33010602011771号