Singleton Pattern


(UCM ELP) #1

Introduction to Java Singleton Pattern

Java Singleton is a software design pattern that premise create a single instance of one class, to be able to call the methods of the class instanced from any part of the program without having to create multiple instances of the same class.
Java Singleton Pattern is one of the Gangs of Four Design patterns and comes in the Creational Design Pattern category.

Implementation of Java Singleton Pattern

For implement the Singleton Pattern, we have different approaches, but all of them have following common concepts.

  • Private constructor to restrict instantiation of the class from other class
  • Private static variable of the same class that is the only instance of the class.
  • Public static method that returns the instance of the class, this is the global access point so that any class can to get instance of the singleton class.

The easier way for me to implement the Singleton Pattern is the one that appears in the following example, but it isn’t the only form of implement:

Related patterns

  • Abstract Factory: many times they are implemented by means of singleton, since normally they must be publicly accessible and there must be a single instance that controls the creation of objects.

  • Monostate: is similar to singleton, but instead of controlling the instantiation of a class, it ensures that all instances have a common state, making all its members class.

I hope it will be of great help to you.


(sreeprasad) #2

This lazy instantiation will cause a race condition.

Best way is to use ENUM


(UCM ELP) #3

As I indicated in the post, it is not the only way to implement it, for my taste it is the easiest to understand, but there are many more and they are better depending on the situation.
But thanks for your contribution