Singleton Design Pattern

How to implement SIngleton Design Pattern in real world application

CONCEPTS

6/12/20242 min read

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful for managing shared resources like configuration settings, logging, or connection pools.

Features:

  • Single Instance: Only one instance of the class is created.

  • Global Access Point: The instance is accessible globally within the application.

Implementation:

The Singleton pattern typically involves a private constructor, a static method to get the instance, and a static variable to hold the instance.

Example in Java:

public class Singleton {

// Private static variable of the single instance

private static Singleton instance;

// Private constructor to prevent instantiation

private Singleton() {}

// Public static method to provide access to the instance

public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

}

return instance;

}

// Other methods of the singleton class

public void showMessage() {

System.out.println("Hello, I am a singleton!");

}

}

public class SingletonDemo {

public static void main(String[] args) {

// Get the single instance of Singleton

Singleton singleInstance = Singleton.getInstance();

// Call the method of the singleton instance

singleInstance.showMessage();

}

}

Example in Javascript

class Singleton {

// Private static variable to hold the single instance

static instance = null;

// Private constructor to prevent instantiation

constructor() {

if (Singleton.instance) {

throw new Error("You can only create one instance!");

}

Singleton.instance = this;

// Other initialization code can go here

}

// Static method to get the instance

static getInstance() {

if (!Singleton.instance) {

Singleton.instance = new Singleton();

}

return Singleton.instance;

}

// Example method

showMessage() {

console.log("Hello, I am a singleton!");

}

}

// Usage

try {

// Attempt to create multiple instances

const singleInstance1 = Singleton.getInstance();

singleInstance1.showMessage(); // Output: Hello, I am a singleton!

const singleInstance2 = Singleton.getInstance();

singleInstance2.showMessage(); // Output: Hello, I am a singleton!

console.log(singleInstance1 === singleInstance2); // Output: true

} catch (e) {

console.log(e.message);

}

Use-cases:

  • Configuration Management: Ensure that configuration settings are consistent throughout the application.

  • Logging: Maintain a single instance of a logger to ensure that log messages are properly synchronized.

  • Resource Management: Manage shared resources like database connections, file handlers, or network sockets.

Benefits:

  • Controlled Access: Provides a controlled access point to the instance.

  • Reduced Global Variables: Reduces the need for global variables, which can be modified from anywhere in the application.

Drawbacks:

  • Single Point of Failure: If the singleton instance encounters an issue, it can affect the entire application.

  • Concurrency Issues: In multi-threaded applications, proper handling is required to avoid race conditions.

The Singleton pattern is a powerful tool for ensuring a class has only one instance, but it should be used judiciously to avoid potential pitfalls related to global state management and concurrency.