简体   繁体   中英

Should I always use static factory methods instead of constructors?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM