I've been researching this after I read Joshua Block's Effective Java Book, Item 1, about using factory static methods instead of constructors. There in the text he defends the use, whenever possible and cites, among other justifications, the possibility of implementing the Singleton or Flyweight standards. It also cites the case of the Boolean class, which wisely uses Flyweight through the valueOf (boolean) method:
public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}
My question is: I understand the advantages of using these patterns, but could not be implemented in the constructor itself? Their use alone does not justify the creation of a static factory method.
No:
new, by specification, always creates a new instance (or fails), sonew Boolean(b)would always return a new instance ofBoolean.Boolean.valueOfreturns a pre-existing instance. This is desirable, because there are only two possible values, so there is simply no point in creating more.