| 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
|
|
|
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.
|
 |
 |
|
|
subject: Static Factory Methods
|
|
|