Reputation: 183
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?
Upvotes: 6
Views: 2007
Reputation: 17923
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.
Upvotes: 2
Reputation: 13097
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.
Upvotes: 5