Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always use static factory methods instead of constructors?

Tags:

java

oop

Reading Effective Java, it seems that there are many advantages, and very few disadvantages, to use static factory methods. By static factory methods I specifically mean the following

public class MyClass {    
  private MyClass() { ... };  

  public static MyClass getInstance() {
    return new A();
  }    
}

From Effective Java:

Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95, p. 107]. The static factory method described in this item has no direct equivalent in Design Patterns.

Now is it best to always follow this practice, or only sometimes?

If so when?

Is is ever overkill to do this?

like image 486
cendrillon Avatar asked Mar 16 '12 05:03

cendrillon


2 Answers

In general, constructors are simpler than Factories, so this is a major reason to choose constructors over Factory. Use Factory when the situation calls for it, no "by default". You should do the simplest thing that solves your problem, and most of the time this would be constructors.

like image 82
Oleksi Avatar answered Oct 13 '22 01:10

Oleksi


A factory approach abstracts the Creation and Configuration of objects from the code using the object.

If all depends the complexity involved in creation and initialization of object. If they are simple then no need to use factory pattern.

If its a bit complex (involving lot of steps in initialization before you use it) and better go with factory pattern.

like image 27
Santosh Avatar answered Oct 13 '22 00:10

Santosh