Thursday, May 3, 2012

Why to prefer static factory methods over constructors to get the object of a class?

Instead of creating objects using new operator you can also use static method to instantiate a class. Code listing:
// instantiating a class using constructor
Dog dog = new Dog(); 

// instantiating the class using static method
Class Dog{
  private Dog(){
  // factory method to instantiate the class
  public static Dog getInstance(){
    return new Dog();
Using static factory methods have both advantages as well as disadvantages. Advantages:
  1. Static factory methods can have different name than class whereas constructors cannot: As methods have names, they convey their purpose clearly as opposed to constructors. A class can have only one constructor with a given signature, developers get around this restriction by changing the order of parameters passed to constructors; In case of methods you can give a different name to resolve the issue.
  2. Static methods support conditional instantiation: Each time you invoke a constructor an object will get created but you might not want that. (for example, in singleton class you will maintain a single object). Or suppose you want to check some condition only then you want to create a new object.
  3. Methods can return subtypes of return type: Suppose there is a class Animal and it has subclass Dog. We have static method with signature
      public static Animal getInstance(){
    then method can return Both objects of type Animal and Dog which provides great flexibility.
  1. If constructor of the class is not public or protected then the class cannot be sub classed: If you ask if there is a workaround to this, there is not. But honestly, it is better as you cannot use inheritance and so you have to use composition which is always better than inheritance any day.
  2. Another disadvantage is you cannot differentiate between static factory methods and regular factory methods: There is no syntactical difference but if you follow some naming convention then it is easy to identify. For example, getInstance() is used in many frameworks to provide the instance of a class (java.util.Calendar, ).
Examples of static factory methods in Java:
  1. Pattern.compile
  2. Calendar.getInstance
  3. Collections.synchronizeCollection
List is very big. References

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai