Saturday, August 13, 2011

JAVA SINGLETON PATTERN CODE


/*
  Java design patter name  :-) SINGLETON PATTERN

  Definition :-)
    This is a most commonly used pattern. It is useful when we want only one instance of a particular class in  
   whole application.
 i) Here in this example i have override the clone() method of object class because it lets the user to create a
    clone object of the class so it violets the singleton pattern. So overriding it will prevent to create clone
    object.
ii)   Here  i have made the method synchronized becuase without it if two request come at the same time to
     create the object then in creates two objects. so synchronized method will prevent multiple access of the
      method at the same time.
  */

/**
 *
 * @author RK
 */

class Engine{

    private static Engine engineObj;
    String message;

    private Engine(){
        message=" I AM A SINGLETON PATTERN CLASS.";
    }

    public static synchronized  Engine getEngineOject(){
        if(engineObj==null){
            engineObj=new Engine();
        }
        return engineObj;
    }

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

public class SingletonPattern {

    public static void main(String RK[]){

        Engine start=Engine.getEngineOject();
        System.out.println(start.message);
     
    }

}

No comments:

Post a Comment