What is Singleton design pattern? Explain with example.

Answered

What is Singleton design pattern? Explain with example.

Ninja Asked on 18th September 2018 in Design Pattern.
Add Comment
1 Answer(s)
Best answer

Singleton pattern is a creational pattern that ensures that only one instance of a class is created per JVM. It provides global point of access to the object. Some practical uses of Singleton pattern are logging, caches, thread pools etc.

Singleton pattern in Java can be created as follows:

  1. Declare private constructor to restrict instantiation of the class from other classes.
  2. Declare private static variable in the class to store the only instance of the class.
  3. Declare public static method that returns the instance of the class. This is the global access point for outer world to get the instance of the singleton class.
public class Singleton {
 private static Singleton instance = null;
 private Singleton() {
 }
 public static Singleton getInstance() {
  if (instance == null) {
   instance = new Singleton();
  }
  return instance;
 }
}

The above basic design for Singleton is not fool proof due to two reasons:

  • It is not thread safe and it is possible to create multiple instances in multiple threads invoke the getInstance method at the same time.
  • The private constructor approach can be broken through reflection
Ninja Answered on 18th September 2018.
Add Comment