Singleton Pattern example using java



Problem faced in Object creation

            Creating an object more than one time that will never chance.

            Example:

                Application that contain xml, property file etc need to load them only once to get the value

                Initializing JDBC driver using class.forName("....");


Solution

            Create one object globally and share it whenever it is needed

 There are different way to achieve this


Solution 1 : Eager initialization (Static block)

                    Object will be created while loading the class itself. Also allows you to handle exception while creating Object

 package com.candidjava.pattern;

public class MyConfig {
		
	private static MyConfig t; // global variable to hold the object
	
	static
	{
		try{
			t=new MyConfig(); // creating object while loading the class
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public static MyConfig getInstance()  // global access point to get Config object
	{
		return t;
	}

	private MyConfig() // avoid external object creation using private constructor
	{
		
	}

}
 
Main function to Test singleton
package com.candidjava.pattern;

public class MainTest {

	public static void main(String[] args) {
	
		MyConfig my1=MyConfig.getInstance();
		MyConfig my2=MyConfig.getInstance();
		
		System.out.println("Verifying singleton");
		System.out.println(my1==my2);
		
	}
}

Output
Verifying singleton true

Solution 2 : Eager initialization (Static object creation)

         same as previous one but does not provide exception handling features

package com.candidjava.pattern;

public class MyConfig {
		
	private static MyConfig t=new MyConfig();;
	
	public static MyConfig getInstance()
	{
		return t;
	}

	private MyConfig()
	{
		
	}

}

Main Program to Test Singleton
package com.candidjava.pattern;

public class MainTest {

	public static void main(String[] args) {
	
		MyConfig my1=MyConfig.getInstance();
		MyConfig my2=MyConfig.getInstance();
		
		System.out.println("Verifying singleton");
		System.out.println(my1==my2);
		
	}
}

Output
Verifying singleton
true

Solution 3 : Lazy initialization

     Object will be created only when it is needed for the first time. 

 package com.candidjava.pattern;

public class MyConfig {
		
	private static MyConfig t;
	
	public static MyConfig getInstance()
	{
		if(t==null)
		{
			t=new MyConfig();
		}
		return t;
	}

	private MyConfig()
	{
		
	}

}
 
Main method to test singleton

package com.candidjava.pattern;

public class MainTest {

	public static void main(String[] args) {
	
		MyConfig my1=MyConfig.getInstance();
		MyConfig my2=MyConfig.getInstance();
		
		System.out.println("Verifying singleton");
		System.out.println(my1==my2);
		
	}
}

Output
Verifying singleton true



Related Post

Comments


©candidjava.com