Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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.
 
Brace yourself while corporate america tries to sell us its things. Some day they will chill and use tiny ads.
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!