Re: a question about factory method
On 18.12.2014 14:57, John wrote:
> I am reading a very good web site
> http://www.javapractices.com/topic/TopicAction.do?Id=21
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:
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).
By using this method authors of that class gain a lot of freedom, notably
- regarding the type of return value
- regarding the point in time when an instance will be created
For example: it may make sense to have different classes for the cases
that imaginary part is 0 and is not 0.
Then, it may be later decided to optimize allocation of Complex
instances and use something like an internal pool (e.g. similar for
small Integer values). If you use a constructor there will be a new
instance _every time_.
By providing the factory method the API for obtaining Complex instances
can stay the same while internally more changes can be done.
Btw. these properties are mentioned at the top of the page that you linked.
I guess most people will do what I do here.
Probably. But that does not mean that this solution is better.
Btw. I wonder why they did not make member fields final. Also it seems,
Complex could be Serializable.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/