Friday, June 27, 2014

Singleton Design Pattern in Java

INTRODUCTION

Singleton design pattern is one of the popular design patterns in java.
The straightforward understanding from the singleton is the single instance. Yes, only one instance of any singleton class can be created throughout the application.

WHEN TO USE

  1. When the business requirement is to create only one instance for the application.
  2. If you want to avoid creating multiple objects for a class.
  3. Need to restrict the creating an object for your class.

HOW TO IMPLEMENT

Java access specifier actually makes the class singleton. How? make the constructor as private so that it can not be extended by other class.
Consider the below example.
public class Singleton {
 // Declare an instance of this class private static
 private static Singleton _singletonInstance;

 /**
  * Make the constructor as private, so that it can't be sub-classed
  */
 private Singleton() {
 }

 /**
  * Has the logic to create a new Instance for Singleton class. static keyword
  * helps to access this method directly. synchronized - helps to avoid
  * multiple instances created by the multiple threads in case.
  *
  * @return
  */
 public static synchronized Singleton getSingletonInstance() {

   if (null == _singletonInstance) {
     _singletonInstance = new Singleton();
   }

   return _singletonInstance;
 }
}


Also, It is marked as static to make method accessible directly using the class name, synchronized makes the method thread-safe so that no other thread can access this method and try to create multiple instances.

Also, I am having simple java class to create multiple instances and test the singleton feature.

public class SampleJava {
 public String getName() {
   return "Sample Java";
 }
}

Now time to test the singleton design pattern. Try to create 2 or more instances for the SampleJava class and check how many instances are actually created.

public class SingletonTest {

 public static void main(String[] args) {

   // Create a instance for the Singleton class
   Singleton s1 = Singleton.getSingletonInstance();

   // Create another instance
   Singleton s2 = Singleton.getSingletonInstance();

   System.out.println("Are s1 and s2 same? : " + (s1 == s2));

   SampleJava sj1 = new SampleJava();
   SampleJava sj2 = new SampleJava();

   System.out.println("Are sj1 and sj2 same? : " + (sj1 == sj2));
 }
}

OUTPUT


Are s1 and s2 same? : true
Are sj1 and sj2 same? : false
Hope this example clarifies the Singleton Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!

No comments :

Post a Comment