Creating and Destroying Objects
1, Consider providing static factory methods instead of constructors
- Named methods
- Flexible: not required to create a new object each time invoked.
- Flexible: can provide an object of any subtype.
- The class without a public or protected constructor cannot be subclassed.
(Tip: prefer composition to inheritance)
- Not readily distinguishable from other static methods. (Tip: using common names like valueOf(), getInstance())
2, Consider a builder when faced with many constructor parameters
The Builder pattern simulates named optional parameters (Java is lack of the useful feature).
3, Enforce the singleton property with a private constructor
a, Public static final field
- Use it if you are sure the class will forever be a singleton
b, Private static final field + static factory method (hide the implementation)
- Use it if the class may not be pure singleton in the future
4, Enforce noninstantiability with a private constructor
Better than making a class abstract: the abstract class can be subclassed which misleads users to think the class is designed to be subclassed (inheritance is not recommended in general).
5, Avoid creating unnecessary objects
Tip: reuse the heavy immutable objects by caching
6, Eliminate obsolete object references
Otherwise obsolete objects cannot be garbage collected.
7, Avoid finalizers
Rational: it won’t work as expected