Singleton Design Pattern

Singleton Design Pattern

If we are talking about Design Patterns, One of the most common pattern that crosses your mind is Singleton Design Pattern.

The underlying definition of the same is “Ensure a class only has one instance, and provide a global point of access to it.”

Even though it is simple and most of you might already know this, but at times it gets confusing, And as there is No right or wrong approach to it, I will discuss a few of the most common approaches in this post.

Approach 1
In this approach we create a static final variable which will hold our unique instance.
Next we make sure that no can access the constructor to create a new instance, So we make the constructor private.
Now in order to allow access to this instance we create a public Static method which returns you the uniquely created instance of our class.

public class Nitin {

private static final Nitin singletonInstance = new Nitin(); // my unique instance

// Private constructor prevents instantiation from other classes
private Nitin() {
}

public static Nitin getInstance() {

return singletonInstance;
// returns you the same instance we created
}
}
}

Approach 2 – using a static block of code to instantiate.


private static Nitin singletonInstance = null; // instance has not been
// created yet.

// Private constructor prevents instantiation from other classes
private Nitin() {
}

static {
singletonInstance = new Nitin();
// ensures that the instance is only created when it is first needed.
}

}

Approach 3 – we can check in the getInstance method if the instance was created. It ensures that your instance is only created when it is needed.

public class Nitin {

private static Nitin singletonInstance = null; // instance not created yet

// Private constructor prevents instantiation from other classes
private Nitin() {
}

public static Nitin getInstance() {

if (singletonInstance == null) {
singletonInstance = new Nitin(); // my unique instance
}
return singletonInstance;
}
}

Well as we say that there is always a way out 🙂 If you want to break something then no one can stop you…

There is a crack to singleton implementation which I came across recently. Even though you should not try that on someone’s code but there is no harm if you just did for fun,

class CrackingSingleton {

public static void main(String[] args) throws IllegalArgumentException,
InstantiationException, IllegalAccessException,
InvocationTargetException, ClassNotFoundException {

Class clazz = Class.forName("Nitin"); // loads the class

Constructor[] cons = clazz.getDeclaredConstructors();
// gets the constructors

cons[0].setAccessible(true); // changes the access rights

Nitin noMoreSingleton = (Nitin) cons[0].newInstance();

// we have our new instance

}
}

[ad]

3 Responses so far.

  1. Ashutosh says:

    Singletons will also not work if Singleton class extends a class & that super class implements clonnable interface & overrides clone method.

  2. Pardeep says:

    Your Singleton implementation was not thread safe :), but anyways your “CrackingSingleton” will work fine unless we properly set the JVM properties.

    Also, Singletons have problem in clustered environment as well 🙂

  3. Pardeep says:

    @ThreadSafe
    public static Nitin getInstance() {

    if (INSTANCE!= null) return INSTANCE; // we are optimistic
    else{
    synchronized(this){ //we do not want two thread to enter this area
    if (INSTANCE== null) { // check for the second thread which enters.
    INSTANCE= new Nitin(); // my unique instance
    }
    }
    return INSTANCE;
    }
    }
    }