Contents

Singleton Pattern

Singleton is a creational [design pattern](@tag/design pattern) that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Why ?

  1. Ensure that a class has just a single instance
    Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resource—for example, a database or a file

  2. Provide a global access point to that instance
    Just like a global variable, the Singleton pattern lets you access some object from anywhere in the program. However, it also protects that instance from being overwritten by other code.

Solution

All implementations of the Singleton have these two steps in common:

  • Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
  • Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.

If your code has access to the Singleton class, then it’s able to call the Singleton’s static method. So whenever that method is called, the same object is always returned.

Applicability

Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program.

The Singleton pattern disables all other means of creating objects of a class except for the special creation method. This method either creates a new object or returns an existing one if it has already been created.

Use the Singleton pattern when you need stricter control over global variables.

Unlike global variables, the Singleton pattern guarantees that there’s just one instance of a class. Nothing, except for the Singleton class itself, can replace the cached instance.

Note that you can always adjust this limitation and allow creating any number of Singleton instances. The only piece of code that needs changing is the body of the getInstance method.

There are two forms of singleton design pattern:

Note
Early Instantiation: creation of instance at load time.
Lazy Instantiation: creation if instance when required.

Advantages and uses of singleton design pattern:

Note
Saves memory because object is not created at each request where single instance is reused again and again.
Singleton pattern is mostly used in multi-threaded and database applications.