When we write java applications, sometimes it is appropriate to have only one instance of a class. Windows Managers, Login and Dialog boxes etc are few examples of such classes. The Singleton design pattern solves this common problem and ensures that the class has only one instance. This also provides global point of access to the object.
In this tutorial, I will show you how you can implement the singleton design pattern in java.
class LoginForm
{
private static boolean instance_flag = false;
private LoginForm()
{ }
public static LoginForm instance()
{
if(instance_flag)
{
return null;
}
else
{
instance_flag = true;
return new LoginForm();
}
}
public void finalize()
{
instance_flag = false;
}
}
Following program is using LoginForm class and creating two objects of it. You can easily see that only first object is created and second object is null.
public class SingletonTest
{
public static void main(String[] args)
{
LoginForm f1 = LoginForm.instance();
System.out.println(f1);
LoginForm f2 = LoginForm.instance();
System.out.println(f2);
}
}