Item 1: Consider static factory methods instead of constructors
Advantage:
One advantage of static factory methods is, unlike constructors, they has names.
A second advantage of static factory methods is, unlike constructors, they was not required to create a new objec T each time they ' re invoked.
A third advantage of static factory methods is, unlike constructors, they can return an object of any subtype of Their return type.
A fourth advantage of static factory methods is that they reduce the verbosity (verbose) of creating parameterized Type Inst Ances.
Disadvantage:
The main disadvantage of providing only static factory methods are that classes without public or protected constructors cannot be subclassed.
A second disadvantage of static factory methods is, they is not readily distinguishable from other static methods .
Item 2: Consider a builder when faced with many constructor parameters
The telescoping constructor pattern works, but it was hard-to-write client code when there was many parameters, an D harder still to read it.
A JavaBean may is in the inconsistent state partway through its construction.
The JavaBeans pattern precludes the possibility of making a class immutable.
Advantage:
The Builder pattern simulates named optional parameters.
Class.newinstance breaks Compile-time exception checking.
The Builder pattern is a good choice when designing classes whose constructors or static factories would has 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.
A single-element enum type is the best implement a singleton.
#1. Singleton with public final field
Public class Elvis { publicstaticfinalnew Elvis (); Private Elvis () {...} Public void leavethebuilding () {...}}
#2. Singleton with Static factory
Public class Elvis { privatestaticfinalnew Elvis (); Private Elvis () {...} Public Static return INSTANCE;} Public void leavethebuilding () {...}}
#3. Readresolve method to preserve Singleton property
Private Object readresolve () { // Return The one true Elvis and let the garbage collector take care of the Elvis impersonator. return INSTANCE;}
#4. Enum Singleton-the Preferred Approach
Public enum Elvis { INSTANCE; Public void leavethebuilding () {...}}
Item 4:enforce noninstantiability with a private constructor
Attempting to enforce noninstantiability is making a class abstract does not work.
A class can is made noninstantiable by including a private constructor.
Public class Utilityclass { // Suppress default constructor for noninstantiability Private Utilityclass () { thrownew assertionerror (); } // remainder omitted}
Java efficient Programming (2)--Creating and destroying Objects