Thursday, July 9, 2015

Effective Java--1)Create/Destroy Object: static factory method

Static factory method

Static factory is another way to create a class instance other than constructor. [1] shows an example:
 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>;}
      
Cons:

  • Class without public/protected constructor cannot be subclassed.
  • Not really distinguishable from other static method.