DEV Community

Cover image for Singleton Pattern
Eyuel Berga Woldemichael
Eyuel Berga Woldemichael

Posted on

Singleton Pattern

Singleton pattern allows creation of only a single instance from a class


Consider a case where your application needs to access a shared resource from different places at various times. And also keep a consistent state between each access.

The Singleton pattern solves this problem by creating a class that is responsible for creating and insuring only a single instance is created, while allowing direct access to the instantiated object.


The Singleton pattern can be used in cases where:

  • The class have exactly one accessible instance


Singleton pattern class diagram


  • Singleton: defines an Instance operation that lets clients access its unique instance


  • Clients access a Singleton instance only through the getInstance method.


  • Can be sure of the number of instances
  • Can globally access instance


  • Violates single responsibility principle. It is responsible for making sure that one instance is being created and also provide the core functionalities of the object itself.
  • It is hard to unit test because global states are hard to isolate.
  • Causes an object to be globally mutable which may not be desired in some cases.


Singletons can be implemented in numerous ways:

  1. Eager initialization: Object of class is created when it is loaded to the memory
  2. Lazy initialization: In this method, object is created only if it is needed.
  3. Thread Safe Singleton: A thread safe singleton in created so that singleton property is maintained even in multi-threaded environment.


The money received by customers of the cafe is stored in a cash register. It is important that there is only one cash register per cafe, so that the income of the cafe is accurately known.

To solve this problem, we implement CashRegister as a singleton. we make the constructor private so nobody can instantiate the class. And we implement a method getInstance to be called by user to obtain instance of the class.

Top comments (0)