问题
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.
- Factory methods have names, it's easier to remember, and less error-prone.
- They do not require a new instance to be created each time they are called, you can use preconstructed classes and cache here.
- They can return an object of any subtype not only the one called in
new
- 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