Factory methods are static methods that return an instance of the native class. Examples in the JDK:
- LogManager.getLogManager
- Pattern.compile
- Collections.unmodifiableCollection, Collections.synchronizeCollection , and so on
- Calendar.getInstance
- have names, unlike constructors, which can clarify code.
- do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.
- can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller. This is a very valuable and widely used feature in many frameworks which use interfaces as the return type of static factory methods.
Example
public final class ComplexNumber { /** * Static factory method returns an object of this class. */ public static ComplexNumber valueOf(float aReal, float aImaginary) { return new ComplexNumber(aReal, aImaginary); } /** * Caller cannot see this private constructor. * * The only way to build a ComplexNumber is by calling the static * factory method. */ private ComplexNumber(float aReal, float aImaginary) { fReal = aReal; fImaginary = aImaginary; } private float fReal; private float fImaginary; //..elided }