Singleton design pattern in Java

Category : Design Patterns | Sub Category : Creational design patterns | By Prasad Bonam Last updated: 2023-07-09 07:23:51 Viewed : 327


Singleton design pattern in Java

The Singleton pattern is a creational design pattern that ensures a class has only one instance, and provides a global point of access to that instance. It is commonly used when you want to restrict the instantiation of a class to a single object, ensuring that only one instance exists throughout the application. Heres an example of implementing the Singleton pattern in Java:

java
public class Singleton { private static Singleton instance; // Private constructor to prevent direct instantiation private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { // Double-checked locking to ensure thread safety if (instance == null) { instance = new Singleton(); } } } return instance; } // Other methods and properties of the Singleton class }

In this example:

  • The Singleton class has a private constructor, preventing direct instantiation from other classes.
  • The instance variable is declared as private static, ensuring that only one instance of the Singleton class is created.
  • The getInstance() method provides a global point of access to the single instance of the Singleton class.
  • In the getInstance() method, the instance variable is checked for null. If null, the code enters a synchronized block to ensure thread safety. Inside the block, it performs another null check and creates a new instance only if one doesnt exist already.

The double-checked locking technique is used to optimize performance by avoiding unnecessary synchronization after the first creation of the singleton instance.

Here is an example of how you can use the Singleton class:

java
public class Main {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
// Both instances should refer to the same object
System.out.println(singleton1 == singleton2);
// Output: true
} }

In the Main class, we obtain two instances of the Singleton class using the getInstance() method. Since the getInstance() method always returns the same instance, the output will be true, indicating that both singleton1 and singleton2 refer to the same object.

Its important to note that the Singleton pattern can have pros and cons, and it should be used judiciously based on the requirements of the application.


Search
Related Articles

Leave a Comment: