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;
}
}
Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: