Singleton Design Pattern

Singleton Design Pattern

Design Patterns Serie

Intent

Creating one-of-a-kind objects for which there is only one instance So, it forces us to use this only instance for that object. It is one of the simplest design patterns.

Problem

Its intent is to control access to some shared resources like a database or a file.
It provides the other classes with a global access point. Although this makes the resources usage efficient, it makes it unsafe as it protects that instance from being overwritten by other code.
We can't implement the Singleton design pattern with a regular constructor since a constructor call must always return a new object by design.

Solution

  • Making the default constructor of the singleton class private, to prevent other objects from using the new operator with the Singleton class so, they won't be able to create a "new" instance from it when using it.
  • Creating a static creation method to act as a constructor. This method calls the private constructor to create an object and saves it. So when other objects call this singleton object this method returns the cached object.

Pros and Cons

Pros

  • Better memory usage.
  • one-time initialization (you initialize the class only one time in the beginning).
  • global access point for singletoned instances.

Cons

  • They inherently cause code to be tightly coupled. This makes faking them out under test rather difficult in many cases.
  • They violate the single responsibility principle: by controlling their own creation and lifecycle.
  • It makes dependencies hidden in the code.

Thank you, and goodbye.