3/09/2007

Singleton Pattern

The Objective of the pattern is,at any given time there can be only one instance of a class.

A singleton pattern can be used to create a Connection Pool. We can have connection object as singleton to avoid wastage of
resources.

Steps to create a singleton pattern,

  1. We need to have default constructor of the class as private, which prevents instantiation of the object by other classes.

  2. Define a static method that returns singleton object, If object doesn't exists new object is returned otherwise existing
    object would be returned.

  3. To avoid the object being cloned, override the clone method of the Object class.

  4. If a application is going to be Multithreaded one then there can be chances wherein two therads at the sametime can access the static method which may create more than one instance of the singleton class. To avoid the above scenario we need to have this static method as synchronized.



class Singleton {
private static Singleton singletonObject;
private Singleton{
}

public static synchronized Singleton getInstance(){
if (singletonObject == null){
singletonObject = new Singleton();
}
return singletonObject;
}

public Object clone()throws CloneNotSupportedException{
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo{
public static void main(String args[]){
//Singleton obj = new Singleton(); Would cause Compilation error.
//create the Singleton Object..
Singleton obj = Singleton.getInstance();

}
}

No comments:

dzone.com