File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java class

 
Anjali Ajwani
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I ensure that a class has only one instance?
 
Dale DeMott
Ranch Hand
Posts: 515
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create the class in a Singleton design pattern. See the "OO, Patterns, UML and Refactoring" group for more details. Basically you will be using a method called instance() to retrieve the instance. if the instance already exists, you will return it, else you will create a new one. There will be a static varaible in the class that will hold the reference to this instance. Initially it is null. Something like the following code.

Hope this helps
-Dale
------------------
What's this H2SO4 doing in my fridge?? ( thud )
[This message has been edited by Dale DeMott (edited June 14, 2001).]
 
Anjali Ajwani
Greenhorn
Posts: 16
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dale. This is what I was looking for.
 
Wirianto Djunaidi
Ranch Hand
Posts: 210
Ruby Ubuntu VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember to make the instance() method synchronized, else
there might be a possibility you end up with more than 1 instance
of the object.
Another way is just make the instance() method return the _instance object, and during declare _instance with:

Most of the VM will do lazy instantiation of that object anyway.
 
rani bedi
Ranch Hand
Posts: 358
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please explain how will it restrict creation of more than one instance in a VM?
I tried to create 2 instances with this code and got successful.
 
AGivant
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't create 2 instance, you just declared i as static. In
this case it doesn't matter how many instance you'll create. Change i from static to non-static and you'll see same result which means we've created only one instance of the class.
Have a nice day.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic