Java Singleton Pattern Tutorial


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Java Singleton Pattern Tutorial

  1. #1
    Join Date
    Jan 2006
    Posts
    16

    Java Singleton Pattern Tutorial

    Singleton Pattern

    The Singleton Pattern is one of the commonly used design templates when there needs to be a control on how an object can be created. 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).
    One such scenario where it might prove useful is when we develop the Java Help Module in a project. JavaHelp 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.
    Implementing the Singleton Pattern
    To implement this design pattern we need to consider the following 4 steps:

    Step 1: Provide a default Private constructor
    Code:
     
    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

    Code:
    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.

    Code:
    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
    Code:
    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.

    Code:
    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.

    Code:
    class Singleton{
      
    	private static Singleton singletonObject;
    	
    	private Singleton(){
    		  //	 Optional Code
    	}
    	
    	public static Singleton getSingletonObject()
    	{
    	    if (singletonObject == null){
    	    	singletonObject = new Singleton();
    	    }
    	    return singletonObject;
    	}
    	
    	public Object clone()throws CloneNotSupportedException
    	{
    	    throw new CloneNotSupportedException(); 
    	}
    		  
    }
    
    public class SingletonObjectDemo{
    	public static void main(String args[]){
    //		Singleton obj = new Singleton();	Compilation error not allowed
    		
    		//create the Singleton Object..
    		Singleton obj = Singleton.getSingletonObject();
    
    		// Your Business Logic
    		
    	}
    }
    Regards,
    Hemanth

  2. #2
    Join Date
    Jan 2006
    Location
    Sydney
    Posts
    49
    It is also a very commonly asked interview question on design patterns.
    Arul

  3. #3
    Join Date
    Jan 2006
    Posts
    16
    Yeah thats the reason why I have submitter this wonderful article. One more topic that would interest with respect to Interviews is exception Handling which is discussed in

    http://www.beginner-java-tutorial.co...xceptions.html

Similar Threads

  1. Java book
    By Lou in forum Java
    Replies: 9
    Last Post: 09-19-2007, 05:58 AM
  2. Java swing tutorial Website
    By hemanthjava in forum Java
    Replies: 2
    Last Post: 10-03-2006, 04:13 PM
  3. Java vs. .Net. A questionnaire
    By Basil in forum .NET
    Replies: 1
    Last Post: 05-13-2005, 06:46 AM
  4. Re: VB vs. Visual Age for Java
    By JJ in forum Enterprise
    Replies: 1
    Last Post: 07-06-2000, 04:50 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center