• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with SingleTon  RSS feed

 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

When I am trying to develop singleton class, It is not behaving like Singleton class.
Please check where I did wrong.
This is my SingleTon class.


To test this singleton i wrote this class,


After the result it is printing below output. But i expeced Instance is always 1 and object is same.
SingleTon Obj>>SingleTon@19821f
Instance 1
SingleTon Obj>>SingleTon@addbf1
Instance 2

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where are you setting your member variable to be non-null? In other words, how do you think you'll ever get into the else block in



Also, when posting code, please UseCodeTags(⇐click) so it will be readable.

And, finally, while this may be a useful academic exercise, the problem you're having only comes about because you're doing lazy instantiation. There is no good reason to do that. Simply instantiate at declaration time.



Or else just use the enum singleton approach.
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really want singleton behavior, one of the first things you need to do is prevent the class from being instantiated by any other class.
 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank Guys for your reply.

But If I do like this there is no singleton object, right?
Share your suggestions.

singletTonObj.clone();
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it. As long as you haven't implemented Cloneable it won't work. And by default clone() is protected.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jami siva wrote:But If I do like this there is no singleton object, right?
singletTonObj.clone();

Depends on how you implement clone(); but if you think about it, the call is nonsensical.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!