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);
     
    }

}

Advertisements

About rajkirpal

i am a software engineer. and i have decent knowledge about java technologies like ANDROID, Servlet, Jsp, Struts, Hibernet, Spring, J2ME, Java Script, Ajax, JQuery, CSS. Further i am Preparing Easy understandable materials/documents upon the same java technologies and developing project in core java , advanced java and j2me , ANDROID as per the requirements Also designing the web sites and logos Thank You.
This entry was posted in J2EE, J2SE. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s