Singleton design pattern
As the name says… Singleton -> means just single.
There are so many situations where we need to create many or one instance of our class. Like we will have a single database connection manger.
There are many ways to create a singleton design (i.e. Using User Defined exception class, using static class).
rather there is the most useful way that most programmer uses. That is static method having a private default constructor.
public class IsSingle {
static boolean instanceFlag = false;
private IsSingle(){}
public static IsSingle getInstance(){
if(!instanceFlag){
instanceFlag = true;
return new IsSingle();
}
else{
return null;
}
}
// finalize is needed here, because if object IsSingle is garbage collected then isInstance must be false to invoke new.
public void finalize(){
instanceFlag = false;
}
}
Advertisement
No trackbacks yet.