Why use a factory instead of 'new'?

谁说我不能喝 提交于 2019-12-14 01:42:31

问题


I am reading the book EMF: Eclipse Modeling Framework where its stated:

The EMF programming model strongly encourages, but doesn’t require, the use of factories for creating objects. Instead of simply using the new operator to create [an object]...

Why is the use of factories encouraged over new?

Your answer does not have to be EMF specific, as long as it has to do with Java.


回答1:


You can read Effective Java Item 1: Consider static factory methods instead of constructors. It describes advantages of using factory methods in detail:

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

  • A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.

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

  • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances (seems to be outdated since Java 7)




回答2:


I agree with mostly every answers given here, but those arguments apply generally to every situation in Java, however in this particular case of EMF there is another additional reason: EMF has its own introspection mechanisms, which are used, for instance, for the serialization and deserialization, which doesn't rely in the Java reflection.

For the deserialization, for instance, it reads the XML file, and instantiate the Java objects using the Ecore model information and the respective Factories. Otherwise it would need to use Java reflection.




回答3:


The answere here is not specific to Java too.

  1. Factory methods have names, it's easier to remember, and less error-prone.
  2. They do not require a new instance to be created each time they are called, you can use preconstructed classes and cache here.
  3. They can return an object of any subtype not only the one called in new
  4. You can parameterize calling "new" object.



回答4:


Mainly it is simplicity of creating objects. It's a lot easier to call method from factory than to remember what each parameter in constructor means + it makes changes in code easier



来源:https://stackoverflow.com/questions/29275248/why-use-a-factory-instead-of-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!