What is singleton pattern? Write an example singleton class?

A singleton class is a class which has only one instance per application. Rather per JVM. This design pattern is extensively used when user needs exactly one instance. For example facade objects, state objects or for global variables (as it permits lazy allocation and initialization which may not happen in all languages).

To make a class singleton, its constructor is made private or protected so that it can not be instantiated. Instead, a getInstance () method is written to return a new instance of that class if it doesn’t exist or return the reference of that object if it already exists. If it’s a multithreaded environment make sure to synchronize the getInstance() menthod.
Conventional way of writing a singleton class is :

public class Singleton {
private static Singleton INSTANCE = null;
// to prohibit instantiation
private Singleton() {
}

public static Singleton getInstance() {
if (INSTANCE == null) {
// lazy initialisation
INSTANCE = new Singleton();
}
return INSTANCE;
}
}

You can synchronise on getInstance() method for a multi threaded environment.

Another thread-safe Java programming language lazy-loaded solution is:

public class Singleton {
private Singleton() {}

// lazy initialisation
private static class SingletonHolder {
private final static Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

Remember a singleton class is one instance per JVM. So if you have your application running in a cluster of servers. Every server will have its own JVM, therefore its own instance of singleton class. In this case, purpose of making a class singleton is not fulfilled. Hence this pattern should be used with care.

Related Post

java.util.regex.PatternSyntaxException: Unclosed character class
Welcome to technical discussion portal
What is an abstract class?
About
Write a function to reverse the words in a string? (e.g. “Your time has come” – > “come has time Your”)

Comments

Leave a Reply