Win a copy of Learning Regular Expressions this week in the General Computing forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

how to make single instance of a class?  RSS feed

 
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
 
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 ]
 
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just implement Singleton design pattern.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!