Advantages:
- Unlike constructors they have names.
If the parameters to a constructor do not, in and of themselves, describe the object being returned, a static factory with a well-chosen name is easier to use and the resulting client code easier to read.
- They are not required to create a new object each time they're invoked.
The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time.
- They can return an object of any subtype of their return type.
This gives you great flexibility in choosing the class of the returned object.
- They reduce the verbosity of creating parameterized type instances.
Unfortunately, you must specify the type parameters when you invoke the constructor of a parameterized class even if they’re obvious from context.
With static factory methods instead of doing:
You can implement:
Then you could replace the wordy declaration above with this succinct alternative:
Disadvantages:
Then you could replace the wordy declaration above with this succinct alternative:
Disadvantages:
- The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
- A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.
They do not stand out in API documentation in the way that constructors do, so it can be difficult to figure out how to instantiate a class that provides static factory methods instead of constructors.
* Effective Java Second Edition, Joshua Bloch
* Effective Java Second Edition, Joshua Bloch
Brak komentarzy:
Prześlij komentarz