Singleton Design pattern

The importance of this pattern is coming from the fact that There are many objects we only need one of, like objects that handle
preferences and registry settings, objects used for logging.
In fact, for many of these types of objects, if we are to instantiate more than one time we will run into all sorts of problems like incorrect program behavior, overuse of resources.
lets how we can constract a class that can work as Singleton . in order to write this class you need to follow these steps

  1. Declare a static variable to hold one instance
  2. constructor is declared private only Singleton can instantiate this class
  3. write a Method that gives us a way to instantiate the class and return an instance from it

here is example
public class SettingCls {
//We have a static variable to hold our one instance of the
private static SettingCls SettingVar;

/*

constructor is
declared private;
only Singleton can
instantiate this class!
*/
private SettingCls()
{
}
//The getInstance() method gives us a way to instantiate the class
//and also to return an instance of it.
public static SettingCls getInstance()
{
/*
If SettingVar is null, then we
haven’t created the instance yet and,if it doesn’t exist, we
instantiate Singleton through its
private constructor and assign
it to SettingVar.
*/
if(null == SettingVar)
{
SettingVar = new SettingCls();

}
// we here return the instance
return SettingVar;
}
// this method is just to check how the class behaves
public String getMessage()
{
return “i am here”;
}
}

here is our main page
public static void main(String[] args) {
// TODO code application logic here
SettingCls InoBJ = SettingCls.getInstance();
System.out.print(InoBJ.getMessage());
}

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 )

Facebook photo

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

Connecting to %s