• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic singleton factory pattern  RSS feed

 
Robert Raps
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I try to look into Generic singleton factory pattern.
But it is rather obscure for what is useful and how it works.
Please, give some explanations.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did you get that example from?

It is not a singleton, because the class is not final and does not have a private constructor. It is therefore possible to create several instances.
 
Robert Raps
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Where did you get that example from?

It is not a singleton, because the class is not final and does not have a private constructor. It is therefore possible to create several instances.

Effective Java-2nd Edition
Joshua Bloch
ITEM 27: FAVOR GENERIC METHODS page 131
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Where did you get that example from?

It is not a singleton, because the class is not final and does not have a private constructor. It is therefore possible to create several instances.

The new UnaryFunction() is a singleton. Its constructor does not have to be private, as it's an anonymous class and can therefore only be called from the code that declares and instantiates it. Since that's done in the initializer for a static field, it will only happen once in the life of the JVM. Or at least, once in the life of the ClassLoader that loads this class.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I see where I was mistaken.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you are doing is creating an instance of that anonymous class, which takes Object as the parameter for its apply method, and then casting that instance several times to take different types of parameter for apply.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!