aspose file tools
The moose likes Java in General and the fly likes Static Factory Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Static Factory Methods" Watch "Static Factory Methods" New topic
Author

Static Factory Methods

Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Hello,

Can anyone help me on how to create Static factory Methods?

I know that Calendar and DateFormat class from Java API use Static Factory implementation.

But I am not really sure how implementation should go as I have read that Static Factory implementation avoids creation of objects multiple times.
How to really achieve that.


So can you please explain with an example.


Thanks,
Sumukh.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Sumukh Deshpande wrote: I have read that Static Factory implementation avoids creation of objects multiple times.

Not really!. actually it depends how you implement the static factory method. singleton class uses this pattern.
example:
this method produce only one instance


this method produce multiple one instance


hope this helps
Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Thanks Seetharaman Venkatasamy.
Got it now.

But I have one more doubt, how does this is a better implementation than standard constructor provider by a class?

Is it that I don't need to refer the API as I am directly using a getInstance() method?

And does it have any relation with thread-safety?
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Sumukh Deshpande wrote:
does it have any relation with thread-safety?

Yes, It will allow you to create an object in the synchronized way with synchronized key word.


typically, static factory method has one advantage over *new Something()* expression, that is expressiveness.

i.e, *getInstance* is more meaningfull than *new Something* .
Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Thanks Seetharaman Venkatasamy I am clear now.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Sumukh Deshpande wrote:Thanks Seetharaman Venkatasamy I am clear now.

You are welcome
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3065
    
    1

I like to use factory methods for value classes. If I have an immutable value class, I provide a factory method and make the constructor private. Most of the time, the factory method will simply call the constructor, but it gives me the freedom to return cached values to the user in the future.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Static Factory Methods
 
Similar Threads
Calendar class
Regarding setDefaultFactory(JspFactory deflt) of JspFactory.
Instance factory methods
All factory methods are from singleton class
modifiers for constructors