Effective Java - Item 1. Consider Static Factory Methods Instead of Constructors
Advantages of static factory methods
Unlike constructors, they can have easy-to-understand method names.
Ramdom rand = new Random();
BigInteger.probablePrime(500, rand);
The BigInteger.probablePrime method above is a factory method that returns a value that is probably prime. Compared with calling a constructor such as new BigInteger(...), it expresses more clearly what kind of BigInteger instance is being created.
Factory methods for type conversion conventionally use method names such as valueOf and of.
Boolean b = Boolean.valueOf(true);
Unlike constructors, they do not need to create a new instance every time the method is called.
Service service = Service.getInstance();
The Service.getInstance() method above can be implemented to create a new instance, or it can be implemented to return a reusable object for efficiency. In a singleton class, this form of factory method is prepared not for efficiency but to return the same instance.
Unlike constructors, they can return an object of any concrete class.
To design by taking advantage of object-oriented polymorphism, method access through interfaces is necessary. A factory method can hide instantiation of the implementation class, so callers can naturally code against the interface.
public static Service createService(ServiceType type) {
switch (type) {
case FOO:
return new FooService()
case BAR:
return new BarService();
default:
return new DefaultService();
}
}
Disadvantages of static factory methods
They are hard to distinguish from other static methods.
Because static factory methods are generally placed alongside ordinary static methods, or class methods, it is harder to understand how to instantiate the class than with constructors. The instantiation method should be documented in the class Javadoc comments.