In a nutshell — Singleton Pattern

Singleton pattern is a creation design pattern. Are you amused by the word “Creational” here? If you wanna understand what it is, then spend some 3 minutes here to understand it.

I followed one of the courses from Coursera to understand this and I’m leaving the course details below in reference section for you.

As mentioned before, Singleton is a creational pattern, which describes a way to create an object. It it powerful technique, but also one of the simplest examples of a design pattern.

Singleton pattern advises to use one object per class and re-use the same wherever required. This might be desirable in order to circumvent conflicts or inconsistencies, by keeping clear which object the program should draw from. Another goal of singleton design pattern is that the single object is globally accessible within the program.

This might raise a question that, “Should we use single object for all the type of classes?”. The answer is simply no. Let’s say we are processing a list of users in a particular project. Here, User could be a class which holds the information specific to one particular user. Whereas UserService could be a class which holds methods that are used to apply business logic on top of User objects. So, we can have the UserService as Singleton to have this object as a common object.

Let’s see an illustration on the same: Let’s take the class defined below. Here, if you see, we are defining the constructor of the class as private which will force the user not to use new to create an object.

// Singleton.java
public class Singleton {

private static Singleton myInstance;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

private String message;

private Singleton() {
//Initialize the objects if required.
}

public static Singleton instance() {
return Objects.nonNull(myInstance) ? myInstance : (myInstance = new Singleton());
}

}

And we can use this class like below to verify how it works,

// SingletonExample.java
public class SingletonExample {

public static void main(String[] args) {

Singleton s1 = Singleton.instance();
s1.setMessage("Message set from s1");
Singleton s2 = Singleton.instance();
System.out.println(s2.getMessage());

}
}

This program will print the following output when we run it,

Message set from s1

Here the object is getting instantiated first whenever required, instead of creating an object during start up. This concept is called Lazy Creation in OOPs.

Another real time example: If you’re familiar with Spring, then you might have come across this most used annotation @Autowired. This annotation is a basic example for Singleton. I’ll give a simple explanation in case you are not familiar with this. On application start-up, all the Component classes will be instantiated and their objects will be added in the Spring Container Pool. Once the object is created, then dependency injection will happen wherever we have added @Autowired annotation i.e., the singleton object of required type will be injected to the function/parameter/local variable which is annotated by taking it from the container pool.

References:
1. Design Patterns by University of Alberta — Coursera
2. Design Patterns: Elements of Reusable Object-Oriented Software — Book