Sunday, April 18, 2010

Singleton class implementation

Singleton Class :
Singleton design pattern lets you to have only one instance of the class .It prevents the direct instantiation of the object as the object is created once and reused mutiple times.

So kto create a singleton class we have to address the following problems:
1.Should prevent direct instantiation
2.Should return single instance which is created only once.
3.Prevent thread problem withe singleton class implemented.
4.Should not be overrriden .



public final class Singleton {
      private static Singleton ref =null;

      private Singletion(){
     //no code
     }

     public static synchronized Singleton getSingletonObj(){
              if(ref==null){
             ref= new Singleton();
             return ref;
             }
             else{
             return ref;
             }
    public Object clone() throws CloneNotSupportedException {
                      throw new CloneNotSupportedException(); 
    }



}


Explanation :
To prevetn the direct instantiation we provided a private constructor
To prevent the threading problem we made the method synchronized
To prevent the class gettting overriden we made it final
To prevent the clonnning of the object we overriden clone method throwing the exception

No comments: