Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

singleton object

 
Consta Chertakovsky
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to prevent singleton object from the object cloning.
I have one solution as implement clone method with throws new UnclonableObjectexception.
If any other way we have to do it?

Apprichiate it
 
John Waugh
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For Singleton check can also be added in constructor to throw exception if object is already there for that class.
 
don brown (aka brownie brownie)
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
perhaps just make the appropriate constructor private?
 
Thomas Taeger
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Consta Chertakovsky:
How to prevent singleton object from the object cloning.
... implement clone method with throws new UnclonableObjectexception.
If any other way we have to do it?

Hello Consta,

the easiest and the normal way is to leave off "implements Cloneable". Then any caller gets a similar exception as the one supposed by you.

Making any constructor private could not keep the singleton from being cloned because clone(), if Cloneable, bypasses any constructor. This bypassing any constructor is the reason for better performance.

Thomas
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic