What is Singleton Design Pattern?

Singleton Pattern is one of the well known and ask most of the times in interview questions in design patterns, if I am not wrong then 90  percent of the cases singleton pattern is asked, but I don’t understand why this is so famous may be due to its criticality and  frequently occur problem in software coding, WHY, WHY WHY…

Is any one has the answer, Think about Performance!!!.

Performance is one of the target for any application and singleton pattern plays a vital role in improving performance, Imagine the application with lots of objects created and none of the object is destroyed by their own and there is  mechanism to destroy of these objects, Now I don’t think anyone will agree for such design or application. Yes here is Singleton pattern come in picture. Create a single instance of a class and use it through out the application.

One scenario I am missing here what will happen, when no of component of application uses single instance of a class, Doesn’t this hamper the application performance. Do we need to create every class as singleton.

I think No No No. So question is Where to use Singleton pattern?

Singleton pattern is generally used to service instance independent or static data where multiple threads can access data at same time. example can be logging class.


Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the Singleton can be easily adjusted to allow more connections.

How to follow or implement Singleton Design Pattern?

Follow the below suedo to implement singleton pattern in class:
  1. Create a private static variable of a class
  2. Create private construtor so that constructor can be called from outside.
  3. Create a public method which will return the instance of class created at step 1.
  4. Implement the cloneable interface and throw CloneNotSupportException so that clonning can not be done for you singleton class.

Cloneable Interface is required to be implement so that Class instance can not be created by Cloning your class instance.

package com.tekhnologia.classloader;
public class MySingleton implements Cloneable {
private static MySingleton _instance;
private MySingleton() {
}
public static synchronized MySingleton getInstance() {
 if (_instance==null) {
  _instance = new MySingleton();
 }
 return _instance;
}
protected Object clone() throws CloneNotSupportedException
{
    throw new CloneNotSupportedException(“A Singleton Class doesn’t support Clone of Object,  use getInstance() for Object”);
}

If you like reading this please spare time to share it with others or share us a feedback to make it better.

2 Comments

  • Anonymous

    Good and simple example. It looks you have handled multi threading and clone problems in your class. It will be great if you can clarify how can the perils like user defined class loader be stopped for creating more instances.

  • Bhanu Pratap

    For specific to this I recommend to have custom classloader which will use findclass as follows

    public Class findClass(String className){
    byte classByte[];
    Class result=null;
    result = (Class)classes.get(className);
    if(result != null){
    return result;
    }

    try{
    return findSystemClass(className);
    }catch(Exception e){
    }
    try{
    if(!classes.containsKey(className)){
    String classPath = ((String)ClassLoader.getSystemResource(className.replace('.',File.separatorChar)+".class").getFile()).substring(1);
    classByte = loadClassData(classPath);
    result = defineClass(className,classByte,0,classByte.length,null);
    classes.put(className,result);
    return result;
    }
    else
    return classes.get(className).getClass();
    }catch(Exception e){
    return null;
    }
    }

    here we have to trick out classloader so that not more than one instance of class can be created. For More Info Custom ClassLoader.