Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!news.swapon.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Robert Klemme Newsgroups: comp.lang.java.programmer Subject: Re: a question about factory method Date: Thu, 18 Dec 2014 15:28:52 +0100 Lines: 47 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: individual.net 1nr32rV+vXpNTClSyyfXugGMQ8kXrbctfRJvuBgG5X16VuFPw= Cancel-Lock: sha1:E2tfZidRG/AQSf7BOWWGLu02Zxc= User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.3.0 In-Reply-To: Xref: csiph.com comp.lang.java.programmer:30581 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/