Singleton Design Pattern Using Java Singleton Design Pattern Using Java

In this tutorial, We’ll learn how to create a Singleton Design Pattern using Java.

Overview

Singleton Design Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category. Singleton design pattern ensures that a class has only one instance and provides a global point of access to it.

Singleton pattern is one of the simplest but most controversial design patterns. This is one of the reason why it is frequently asked in technical interviews.

Let’s create a Singleton class and also answer these follow up questions:-

  1. How to make singleton class thread safe?
    using double checked locking
  2. How to prevent deserialization to create new object of singleton class?
    using readResolve method to return same instance
  3. How to prevent cloning to create a new object of singleton class?
    override clone method to return same instance
  4. How to prevent reflexion to create a new object of singleton class (assume one instance already exist)?
    throw exception from private constructor if instance already exist

Implementation

Singleton Class
package com.abc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * @author aklahoti
 *
 */
public class Singleton implements Serializable, Cloneable{

 private static final long serialVersionUID = 1L;

 private static Singleton instance = null;
 
 private static Object DUMMY_OBJECT = new Object();
 
 private Singleton(){
  /*To prevent object creation using reflection*/
  if(instance!=null){
   throw new InstantiationError( "Singleton Object is already created." );
  }
 }
 
 public static Singleton getInstance(){
  /*Double checked locking*/
  if(instance == null){
   synchronized (DUMMY_OBJECT) {
    if(instance == null){
     instance = new Singleton();
    }
   }
  }
  return instance;
 }
 
 public static void print(){
  System.out.println("I am a singleton class.");
 }
 
 /*To prevent object creation using deserialization*/
 private Object readResolve() throws ObjectStreamException{
  return instance;
 }
 
 /*To prevent object creation using cloning*/
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return instance;
 }
}