Friday 23 August 2013

Top Most Java Singleton Design Pattern


       Java has several design patterns Singleton Pattern being the most commonly used design pattern. Java Singleton pattern belongs to the family of design patterns, that govern the instantiation process. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM. 
    The Singleton class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the singleton object as it then makes this method a class level method that can be accessed without creating an object.
    One such scenario where it might prove useful is when we develop the Java Help Module in a project. Java Help is an extensible, platform-independent help system that enables authors and developers to incorporate online help into applications. Since at any time we can do only with one main Help object and use the same object in different screens, Singleton Pattern suits best for its implementation.
    A singleton pattern can also be used to create a Connection Pool. If programmers create a new connection object in every java class that requires it, then its clear waste of resources. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the Java application.

Implementing the Singleton Pattern

    To implement this design pattern we need to consider the following 4 steps:
Step 1: Provide a default Private constructor
public class SingletonObjectDemo
{
        //Note that the constructor is private
        private SingletonObjectDemo ()
        {
               // Optional Code
        }
}
 
Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonObjectDemo{
        private static SingletonObject singletonObject;
 
        //Note that the constructor is private
        private SingletonObjectDemo (){
               // Optional Code
        }
 
    public static SingletonObjectDemo getSingletonObject(){
      if (ref == null){
          singletonObject = new SingletonObjectDemo ();
       }
        return singletonObject;
 
    }
        
}
    We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.
Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized SingletonObjectDemo getSingletonObject()
    It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one singleton object being created. This could violate singleton pattern principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration
Step 4: Override the Object clone method to prevent cloning.
  We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
    This again violates the Singleton Design Pattern's objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.
public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException(); 
}
    The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class SingletonClass{
  
        private static SingletonClass singletonObject;
        
        /** A private Constructor prevents any other class from instantiating. */
        private SingletonClass(){
                 //     Optional Code
        }
        
        public static synchronized SingletonClass getSingletonObject()
        {
            if (singletonObject == null){
                singletonObject = new SingletonClass();
            }
            return singletonObject;
        }
        
        public Object clone()throws CloneNotSupportedException
        {
            throw new CloneNotSupportedException(); 
        }
                 
}
 
public class SingletonObjectDemo{
        public static void main(String args[]){
//             SingletonClass obj = new SingletonClass();   Compilation error not allowed
               
               //create the Singleton Object..
               SingletonClass obj = SingletonClass.getSingletonObject();
 
               // Your Business Logic
               System.out.println("Singleton object obtained");
               
        }
}
Another approach to using Singleton pattern

We don't need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing of singletons that may cause other problems.

public class SingletonClass {
        private static SingletonClass ourInstance = new SingletonClass(); 
        public static SingletonClass getInstance() { 
               return singletonObj; } 
        private SingletonClass() { 
        } 
}
 
    In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your Singleton class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the Singleton class when the application is running.

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt