Singleton, one is enough: Software Design Patterns in Java

Akshay Saxena
3 min readFeb 14, 2021

Every design pattern is the outcome of engineers devising globally applicable solutions to frequently common problems faced by them.

Singleton pattern solves two such problems:

  • Ensures that a class has just one instance.
  • Provides a global access point to that instance.

Singleton is a creational design pattern that makes sure that a class has only one instance while providing a global access point to it.

Real-World Analogy

Let us consider the example of an airport and the control tower in it which controls important communications between flights and ground control staff.

Every airport has a control tower and it makes sure all the flight taking off or landing in the airport communicate with the one and only control tower.

The control tower is also the global access point that identifies control staff in charge.

Structure

All implementations of Singleton have two steps in common:

  • The default constructor should be made private, preventing other objects from creating an instance of this class using the new operator.
  • Create a static helper function getInstance() which calls the private constructor to create an object and save it to a static field.

Pseudocode

A naive implementation of Singleton class:

public class Singleton {    // The field for storing the singleton instance should be
// declared static.

private static Singleton instance;
// The singleton's constructor should always be private to
// prevent direct construction calls with the `new`
// operator.

private Singleton() {
//Some initialization code.
}
// The static method that controls access to the singleton
// instance.

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

Singleton class can be initialized in many different ways:

  • Eager Initialization-the instance of the class is created at the time of class loading.
  • Lazy Initialization-the instance of the class is created as an when needed.
  • Thread-Safe-the instance of the class can only be accessed by one thread at a time making it thread-safe.
  • Enum-Since Java Enum values are globally accessible and are only instantiated once.

Pros

  • Makes sure that a class has only one instance.
  • The instance can be accessed globally in your application.
  • Initialised only when required.

Cons

  • Violates the Single Responsibility Principle.
  • Difficult to test.
  • Thread-safety bugs.
  • Also considered as an anti-pattern.

We come to an end of our article, I hope it gave you an insight into Design patterns and Singleton design pattern.

Github: https://github.com/offthebench/java-from-scratch/tree/master/src/com/company/designpatterns/creational/singleton

Happy learning!

--

--

Akshay Saxena

Founder @Fundbakery. The fun on the journey is more interesting than the excitement of arrival.