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 mean the following

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

From efficient Java:

Note that the static factory method does not match the factory method template from the design patterns [Gamma95, p. 107]. The static factory method described in this element has no direct equivalent in design patterns.

Now is it better to always follow this practice or only occasionally?

If so, when?

Is it too hard to do?

+6
source share
2 answers

In general, constructors are simpler than factories, so this is the main reason for choosing constructors over Factory. Use Factory when the situation requires it, there is no "default". You have to do the simplest thing that solves your problem, and most of the time it will be the constructors.

+5
source
An approach

A factory abstracts objects. Creating and configuring objects from code using an object.

If it all depends on the complexity associated with creating and initializing the object. If they are simple, then you do not need to use the factory pattern.

If it's a bit complicated (with a lot of steps to initialize before you use it), and better use the factory template.

+2
source

Source: https://habr.com/ru/post/910878/


All Articles