Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to make single instance of a class?

 
Kartik Mahadevan
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I have to make a class which can be created only once .How do I do it ?

Regards
M.Kartik
 
BalajiS Sridharan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
make the constructor private and have a public static method which will instantiate a instance but before instantiating check whether the variable is null or not

e.g.

public class SingleInstance
{
private SingleInstance()
{


}

private singleInstance;


public static SingleInstance returnSingleInstance()
{
if(singleInstance == null)
{
singleInstance = new SingleInstance();
}
return singleInstance;

}
}
[ September 05, 2005: Message edited by: BalajiS Sridharan ]
 
David Ulicny
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just implement Singleton design pattern.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic