Java Singleton Design Pattern Example



Java Singleton Design Pattern Example


Some simple code to demonstrate the singleton design pattern

Java example

-----------------------------------------------------CODE---------------------------------------
class start
{
public static void main(String args[])
{
                ///CALL THE GETINSTANCE METHOD TWICE///

Singleton.getInstance();
Singleton.getInstance();
}
}


-------------------------------------------------------------------------------------
class Singleton
{
private static Singleton firstInstance=null;

       //BUILD CONSTRUCTOR METHOD 
private Singleton()
{
System.out.println("The Singleton Pattern");

}

       // LAZY INSTANTIATION
public static Singleton getInstance()
{
if (firstInstance==null)
{
firstInstance = new Singleton();
}
return firstInstance;

}
}

----------------------------------------OUTPUT-----------------------------------

The Singleton Pattern

------------------------------------------------------------------------------------

Although the getInstance() method is called twice, only one output will show...

No comments:

Post a Comment