Singleton is one of the Gangs of Four (GoF) Design patterns and comes in the Creational Design Pattern. From the definition, it seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic. We will discuss all about Singleton design pattern principles and different ways to implement Singleton pattern.
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in a single java virtual machine (JVM) . The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, DB Connection, caching etc. Singleton design pattern is also used in other design patterns like Factory, Builder, Prototype etc. In Java the java.lang.Runtime and java.awt.Desktop are implemented using Singleton design pattern.
Singleton pattern is implemented by following common concepts.
- Private constructor to restrict instantiation of the class from other classes.
- Private static variable of the same class that is the only instance of the class.
- Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
- In subsequent sections, we will learn different approaches for Singleton pattern implementation.