Wednesday, 23 May 2012

JAVA: Implementing Singleton design patten for creating single instance with example.

As per the old post related to singleton design patten , here the example of implementation.For implementing the singleton design patten for creating single instance of a class , below one example for better understanding:

//Class with Main function for calling singleton class
public class TestSingleTon {

    /**
     * @param args
     */

    public static void main(String[] args) {
    SingleTonClass classinstance=SingleTonClass.getInstance();
    System.out.println("My SingleTon member value is="+classinstance.testval);
    }

}


//Singleton class 
public class SingleTonClass {

    //create an instance
    private static SingleTonClass my_instance=new SingleTonClass();
   
    private SingleTonClass(){
        //Private Constructor here
        //Not allow to create an object out side
    }
   
    //method to access the instance
    public static SingleTonClass getInstance(){
        return my_instance;
    }
   
    //Member variable
    int testval=10;
   

     //if remove comment from below line , the program will not execute.
    //SingleTonClass s1=new SingleTonClass();
   
}


The output of this program is :-

My SingleTon member value is=10

This is the simple implementation & ensuring one object creation of singleton design patten.Also there are so many other methods are there for implementing signleton ( lazy loading, multiple jvm, etc ).

Thank you
Good Reading.