Source Effective Java
/*Item 1: Consider static factory methods instead of constructors
## Use static method to make instance controlled classes
* The normal way for a class to allow a client to obtain an instance of itself is to provide
* a public constructor. There is another technique that should be a part of every
* programmer’s toolkit. A class can provide a public static factory method, which is
* simply a static method that returns an instance of the class. Here’s a simple example
* from Boolean (the boxed primitive class for the primitive type boolean). This
* method translates a boolean primitive value into a Boolean object reference:
*/
public static Boolean valueOf( boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE ;
}
/*page - 27
One advantage of static factory methods is that, unlike constructors, they
have names. If the parameters to a constructor do not, in and of themselves,
describe the object being returned, a static factory with a well-chosen name is easier
to use and the resulting client code easier to read
page - 29
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 This
allows immutable classes (Item 15) to use preconstructed instances, or to cache
instances as they’re constructed, and dispense them repeatedly to avoid creating
unnecessary duplicate objects
*/
/*Item 1: Consider static factory methods instead of constructors
## Use static method to make instance controlled classes
* The normal way for a class to allow a client to obtain an instance of itself is to provide
* a public constructor. There is another technique that should be a part of every
* programmer’s toolkit. A class can provide a public static factory method, which is
* simply a static method that returns an instance of the class. Here’s a simple example
* from Boolean (the boxed primitive class for the primitive type boolean). This
* method translates a boolean primitive value into a Boolean object reference:
*/
public static Boolean valueOf( boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE ;
}
/*page - 27
One advantage of static factory methods is that, unlike constructors, they
have names. If the parameters to a constructor do not, in and of themselves,
describe the object being returned, a static factory with a well-chosen name is easier
to use and the resulting client code easier to read
page - 29
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 This
allows immutable classes (Item 15) to use preconstructed instances, or to cache
instances as they’re constructed, and dispense them repeatedly to avoid creating
unnecessary duplicate objects
*/