Monday, December 02, 2013

Java Singleton Design Pattern

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best way to create an object.
This pattern involves a single class which is responsible to creates own object while making sure that only single object get created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

Implementation

public class SingleTonClass {

   //create an object of SingleTonClass
   private static SingleTonClass INSTANCE = new SingleTonClass();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleTonClass(){}

   //Get the only object available
   public static SingleTonClass getInstance(){
      return INSTANCE;
   }

   public void showMessage(){
      System.out.println("Hello World!");
   }
}
public class SingletonPatternDemo {
   public static void main(String[] args) {

      //illegal construct
      //Compile Time Error: The constructor SingleTonClass() is not visible      //SingleTonClass object = new SingleTonClass();
      //Get the only object available
      SingleTonClass object = SingleTonClass.getInstance();

      //show the message
      object.showMessage();
   }
}
In above code snippet, we have declared a static object reference to SingleTonClass class called INSTANCE and is returned every time getInstance() is called. In this design, the object will be instantiate when the class will be loaded and before the method getInstance() is being called. Demand loading (lazy loading) also called initialization on demand holder idiom is not seen in this implementation.
We can change this code to add lazy init (Instantiate only when first time getInstance() is called) into this. Following is the code snippet for that

public class SingleTonClass {

   //create an object of SingleTonClass
   private SingleTonClass INSTANCE = null;

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleTonClass(){}

   //Get the only object available
   public static SingleTonClass getInstance(){                                                                                                                            if(INSTANCE==null){                                                                         INSTANCE  = new SingleTonClass ();                                                                  }                                                                               return INSTANCE;                                                                                 }                                                                               public void showMessage(){                                                                           System.out.println("Hello World!");                                                     }                                                                                  }

Why Do we need Singleton pattern?

Singletons are useful only when we need one instance of a class and it is undesirable to have more than one instance of a class.
When designing an application , we usually want to control how an object is used and prevent users (including ourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.

Problem with Singletons

A simple design pattern like Singleton also has few problem:

Construct in a multi-thread environment

It may happen that in a multi-threaded environment two or more threads enter the method getInstance() at the same time when Singleton instance is not created, resulting into simultaneous creation of two objects.
Such problems can be avoided by defining getInstance() method synchronized.
public static synchronized SingleTonClass getInstance() { }

4 comments:

  1. The article is good about Singleton Design pattern. Can you provide different design patterns used in software development.

    ReplyDelete
  2. Sure, will provide most use full design patterns soon.

    ReplyDelete
  3. How can be solved the problem of Singleton in multi-thread environment please ?

    ReplyDelete
    Replies
    1. Hi Marc,

      It can be solved by defining getInstance() method as synchronized.

      Delete

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...