a question about factory method
Hi:
I am reading a very good web site
http://www.javapractices.com/topic/TopicAction.do?Id=21
I have a question about the following code:
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
}
The code uses a private constructor and the factory method. I also notice t=
his class is an immutable class. If I write this class, I would simply have=
a public constructor, like:
public final class ComplexNumber {
public ComplexNumber(float aReal, float aImaginary) {
fReal = aReal;
fImaginary = aImaginary;
}
private float fReal;
private float fImaginary;
//..elided
}
Could you explain to me why their code is better than mine? If theirs is si=
ngleton, I would agree. But in this case, it does not make sense for using =
singleton. The only thing I can think of is using their code is more like f=
ollowing a trend, e.g. String.valueOf(xxx).
I guess most people will do what I do here.