domingo, 13 de mayo de 2012

1) Consider static factory methods instead of constructors

The simple way to instantiate an object in Java is through of constructors, but we can do this whit a static factory method, the static factory methods are methods for create objects. 

Example:

public static Boolean valueOf(boolean b){
    return b ? Boolean.TRUE : Boolean.FALSE;
}

Advantages:

 -We can write whatever name to the method, a diference to constructors we should name it with the same name of the class. This permits write clearer names, names more descriptives a diference to overwrite any numbers of constructors.

-Static factory methods aren't required to create a new object each time they're invoked. This useful when we need control the number of instances also allow use Singleton objects.

-We can return an object of any subtype of their return type. That's give you great flexibility, inclusive you can return a subtype objects without public constructor.

-The static factory methods reduce the verbosity of creating parameterized type instances. 



Disadvantages:

-The classes without public or protected constructors can't be subclassed. That's isn't good certainly but you can suggest composition instead of inheritance.

-You can't distinguish static factory methods from other static methods. But you can use some common names for static factory methods:

  • valueOf
  • of
  • getInstance
  • newInstance
  • getType
  • newType

No hay comentarios: