Search This Blog

Sunday, 9 October 2016

Singleton design pattern Demo

                                  Singleton design pattern Demo
Singleton pattern ensures that only one instance of the class exists in the java virtual machine.It provides a way to access instance of the class through factory method.

synchronized block - In multi thread environment; it gives access to single thread and it ensures that only one instance exists to class
final in class declaration - It will not allow to create subclass; privents inheritance
Colonable - need to override which should not allow to colone the object
Serializable - need to override readReslove method which should not create another object while desralizing object

final public class SingletonClass implements Cloneable, Serializable{
   
    private static SingletonClass myObj;
   
    //Private constructor
   
    private MySingletonClass(){
       
    }
   
    //A static method to get instance.
    public static MySingletonClass getInstance(){
synchronized {
                if(myObj == null){
     myObj = new SingletonClass();
}
        }
        return myObj;
    }
   
    // clone method overridding
    public Object clone() throws  CloneNotSupportedException{ 

return new CloneNotSupportedException("Clone Not Supported Exception.......");
    }
   
    public Object readResolve() {
      return SingletonClass.getInstance();
   }
   private void writeObject(ObjectOutputStream oos) {
      try {
      ----------------
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   private void readObject(ObjectInputStream ois) {
       try {
       ----------------
       } catch (Exception e) {
          e.printStackTrace();
       }
   }  

   @Override
   public String toString() {
      return "Singleton toString....";
   }
}

public class MySingletonDemo {
    public static void main(String a[]){
        MySingletonClass st = MySingletonClass.getInstance();
        ------------------------------
   }
}

No comments:

Post a Comment