Singleton pattern purpose, strategy, usage and example

Singleton Pattern is one of the Gangs of Four Design Patterns and comes in Creational Design Patterns that restricts the instantiation of a class and ensures only one object of the class exists in the JVM (java virtual machine)

Purpose of singleton pattern

There should be only one instance allowed for a class and we should allow global point of access to that single instance.

Singleton pattern implementation strategy
  • We hide the constructor of the class and don’t allow even a single instance for the class. This is done by declaring all the constructors of the class to be private.
  • Define public static method (getSingletonInstance()) that returns the reference to the only instance of the class.
  • The singleton instance is usually stored as a private static variable and the singleton instance is created when the variable is initialized.
Singleton pattern example

Where exactly the singleton design pattern is used in real application?

We use this pattern for logger classes, configuration classes, caching classes etc.,

Leave a Reply

avatar
  Subscribe  
Notify of