Singleton Design Pattern (Creational Design Pattern)

Arguably, one of the easiest design pattern to understand.

Problem
Application needs one and only one instance of an object which is lazily initialized and can be accessed globally.

Explanation
At times, it is important for a class to have exactly one instance of an object. For example, there should be only one open instance for a database connection, for more reasons than one. Or, only one file system and window manager. You only need one class to manage the state of the application.

To ensure that the object is accessible from everywhere, we need a global variable, but using global variable doesn’t keep us from instantiating multiple objects.

We can, instead, delegate the responsibility of keeping track of its sole instance to the class itself. The class can make sure that only one instance of itself can ever be created and provide ways to access that instance. This is singleton pattern.

A singleton class ensures that the class has only one instance and is responsible for creation and access of that instance. It does this by hiding the constructor of the class and defining a public static operation that returns the sole instance of the class.

Singleton UML

Singleton Example in Java

Example 1- A simple singleton with lazy initialization

The instance is created when getInstance() is called for the first time and is set to the variable instance. In the next call to getInstance(), instance is not null, so the if condition is skipped and the instance in returned.
This is the lazy way to create a singleton, in which the instance is created only if it is needed.
This is not a thread safe way to create a singleton, as multiple threads can have their own instance of MySingleton.

Example 2- Lazy initialization with Double check lock

The volatile keyword makes sure that all threads see the same instance of the class, and synchronization inside method makes sure that only one thread is accessing the inner if block at one time.
The object is created when it is first needed.

Uses of Singleton Design patterns
Singleton pattern is commonly used in the following scenarios:

  • State objects are singletons.
  • Many other design patterns, like abstract factory, builder, prototype and Facade uses singletons in various forms.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store