Re: a question about factory method
The factory can do several thing for you.
One important thing is hiding what the actual class is of the objects it
creates. As soon as user programs start using "new ComplexNumber" all
over the place this will be set in stone forever.
Let's say your application uses a significant amount of complex values
from the real plane only (having an imaginary value of 0). You could
create a subclass RealComplex that only holds a single float member and
that always returns 0 for the imaginary part.
Depending on the type of objects the factory creates and their
immutability it could also be a good idea to reuse/singleton common
values or use some LRU cache to achieve a certain level of reuse.
And you could do all this as an afterthought without changing any user
code. It would just require a minor change to your factory method.
Most people might start out doing it the way you intended to and then
later on suffer the consequences. More experienced people will probably
prefer the factory method route.
Silvio
On 12/18/2014 02:57 PM, John wrote:
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 this 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 singleton, 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 following a trend, e.g. String.valueOf(xxx).
I guess most people will do what I do here.