TechnologyZer
technologyzer.com

Singleton Design Pattern

Singleton design pattern is a creational pattern that ensures a class has only one instance and provides a global point of access to that instance. It is commonly used in scenarios where there should be exactly one instance of a class, such as managing shared resources, configuration settings, or centralized logging.

Imagine you have a special key that opens a unique treasure chest in a room. Now, the Singleton pattern is like ensuring there’s only one key and one chest in the entire house. No matter how many people come to the house, they all share the same key to open the same chest. This ensures that everyone accesses the same treasure, and we don’t end up with multiple keys or chests causing confusion. In programming, the Singleton pattern is used to make sure that there’s only one instance (like the key) of a particular class (like the chest) available to all parts of the program. It helps keep things organized and prevents unnecessary duplication.


~:Sample code for Singleton Design Pattern:~

public class Singleton {
// Static instance variable
private static Singleton instance;
private int value;

// Private constructor to prevent instantiation from outside
private Singleton() {
// Initialization code, if any
}

// Static method to get the singleton instance
public static Singleton getInstance() {
// Lazy initialization
if (instance == null) {
instance = new Singleton();
}
return instance;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

// Other methods and variables can be added here
}

public class Main {
public static void main(String[] args) {

// Get the singleton instance
Singleton obj1 = Singleton.getInstance();
obj1.setValue(5);
System.out.println(obj1.getValue());

Singleton obj2 = Singleton.getInstance();
System.out.println(obj2.getValue());

// Use the singleton instance
// ...
}
}

Leave a Comment