Tuesday 29 May 2012

Singleton pattern


Singleton in java :

-> Singleton is one of the design pattern in java which is used to control the creation of class's instance. We can ensure only one instance of the class is created.

-> For this, we need to do something as follows,

1. Make class contructor as private, so that outside world can not access this class.
2. Need to create static variable for class instance.
3. Then, Need to create static method to return instance of singleton class. If class's instatnce is empty, then create new instance and return that instance. Otherwise return already created instance.
4. Make access method synchronized to prevent threading problems.


Example Code :
package javaexamples;

import java.util.Date;

public class SingletoneObjectDemo {

    private static SingletoneObjectDemo singletoneObj = null;

    private  SingletoneObjectDemo() {

    }

    public static synchronized SingletoneObjectDemo getInstance() {
        if (singletoneObj ==null) {
            singletoneObj = new SingletoneObjectDemo();
        }
        return singletoneObj;
    }

    protected void displayDate() {
        System.out.println("Today date is : " +(new Date()).toString());
    }
}


package javaexamples;

public class SingletoneObjImp {
    public static void main(String args[]) {
        SingletoneObjectDemo singletoneObj = SingletoneObjectDemo.getInstance();
        singletoneObj.displayDate();
    }
}

1 comment:

  1. hello sir/madam
    i read your post interesting and informative. i am doing research on bloggers who use effectively blog for disseminate information.i glad if u wish to participate in my research. if you are interested please contact me through mail. thank u

    ReplyDelete