Friday 22 April 2011

how to make class Singleton

Singleton Design Pattern Example Program
>> Monday, April 18, 2011

Singleton Design pattern will allow only one object per Class(JVM).

Before Writing Singleton Design pattern you should follow these steps.

#1). create an instance as static and return type as The same class, and it should be assigned as null.

private static Singletonn instance = null;



#2). "Create a Constructor as private" to deny the creation of object from other class.

private Singletonn(){
       
    }



#3). Write a static method to create object for our class.It should be Once for a class.

public static Singletonn getInstance(){

}



#4). At last return the class Object.


Here We are creating the object once only not again and again.The first time created object is returning again when you called.

package javabynataraj.basic;

class Singletonn {
    private static Singletonn instance = null;
    private Singletonn(){
       
    }
    public static Singletonn getInstance(){
        if(instance==null){
            instance = new Singletonn();
        }
        return instance;
    }
}

public class Singleton{
    public static void main(String[] args) {
        System.out.println("before calling ...");
        System.out.println(Singletonn.getInstance());
        System.out.println("Once Called");
        System.out.println(Singletonn.getInstance());
        System.out.println("Second time called");
    }
}

1 comment:

  1. Very Good Explanation with a neat Program.

    Thanks. I saw this program in javabynataraj blog.

    http://javabynataraj.blogspot.com

    ReplyDelete