Why use factory instead of 'new'?

I am reading an EMF: Eclipse Modeling Framework book that states:

The EMF programming model strongly recommends, but does not require, the use of factories to create objects. Instead of just using a new operator to create [object] ...

Why use rewards for new ?

Your answer should not be EMF specific if it is Java related.

+3
source share
4 answers

You can read Effective Java Element 1: Consider static factory methods instead of constructors. It describes the benefits of using factory methods:

  • One of the advantages of static factory methods is that, unlike constructors, they have names

  • The second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time theyre called.

  • The third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of the return type.

  • The fourth advantage of static factory methods is that they reduce the verbosity of creating instances with a parameterized type (seem to be deprecated since Java 7)

+7
source

I agree with most of the answers given here, but these arguments apply in general to every situation in Java, however in this particular case EMF has one more additional reason: EMF has its own introspection mechanisms, which are used, for example, for serialization and deserialization that does not rely on Java reflection.

For deserialization, for example, it reads an XML file and instantiates Java objects using Ecore model information and associated factories. Otherwise, he will need to use Java reflection.

+1
source

Sure, this does not apply to Java.

  • Factory methods have names; they are easier to remember and less error prone.
  • They do not require creating a new instance with every call, you can use pre-constructed classes and caching here.
  • They can return an object of any subtype, not just the one called in new
  • You can parameterize the call of a "new" object.
0
source

This is mainly the simplicity of creating objects. It is much easier to call a method from factory than to remember that each parameter in the constructor means +, it makes changes to the code easier

-1
source

All Articles