How to use "Static factory methods" instead of constructors?

java

Solution

See here for a nice exposition of the main reasons you might want to do this. In summary:

- Named "constructors".

- Can return null, if appropriate.

- Can return an instance of a derived class, if appropriate.

- Reduce verbosity when instantiating variables of generic types.

Another reason comes to mind that the article doesn't mention: Can implement interesting logic to avoid creating new objects all the time (caching based on parameters, recycling, etc.).

Problem

Effective java says "Consider providing static factory methods instead of constructors" If you have a ``` class A { public static A getInstance() { return new A(); } } ``` Does it make sense to provide this method for class A , rather than call new A() in the code.

Original source

Related problems