Singleton Design Pattern

The singleton design pattern is a design pattern that ensures that a class has only one instance, and provides a global access point to that instance. This can be useful in cases where you want to limit the number of instances of a class that can be created, or where you want to make sure that all parts of an aplication are using the same instance of a class.

To implement the singleton design pattern in Apex, you can follow these steps:

Define a private constructor for the class, which prevents other classes from creating new instances of the class using the new operator.

Define a private static field for the class that will hold the single instance of the class.

Define a public static method for the class that returns the single instance of the class. If the instance has not been created yet, the method should create a new instanse and assign it to the private static field. If the instance has already been created, the method should return the existing instance.

Here is an example of how the singleton design pattern might be implemented in Apex:

/*
* @description: Apex Singleton Design Pattern
* @author: sfdc4u.com
*/
public class MySingletonClass {
    private static MySingletonClass instance;
    private MySingletonClass() { }
    public static MySingletonClass getInstance() {
        if (instance == null) {
            instance = new MySingletonClass();
        }
        return instance;
    }
}

 

To use the singleton class, other parts of your code can call the getInstance() method to get a reference to the single instance of the class like below:

MySingletonClass instance = MySingletonClass.getInstance();

 

When to use Singleton Design Pattern?

Singleton design pattern can be used for logging and caching related implementation. This patern can also be used with other design patterns like Abstract Factory and more.

1 thought on “Singleton Design Pattern”

Leave a Comment