Static factory method
public static Boolean valueOf(boolean b){
return b? Boolean.TRUE:Boolean.FALSE;
}
Static factory is a special kind of static method. Static factory returns a class instance.
Pros:
- Static factory has name. Constructor doesn't have name, sometimes may call the wrong constructor.
- Do not require to create a new object each time they are invoked.
- Like Flyweight technique, greatly improve performance if equivalent objects are requested often, especially when they are expensive to create.
- Can return any subtype of their return type.
- Like EnumSet returns a single long if no more than 65 elements; otherwise backs a long array.
- Static factory reduces the verbosity of creating parameterized type instance.
- Constructor flavor:
public static Boolean valueOf(boolean b){ return b? Boolean.TRUE:Boolean.FALSE; } - Static factory method flavor:
Map<String,List<String>> m = HashMap.newInstance(); public static <K,V> HashMap<K,V> newInstance(){ return new HashMap<K,V>;}
- Class without public/protected constructor cannot be subclassed.
- Not really distinguishable from other static method.