top of page

Singleton Pattern in Apex

Updated: Apr 17, 2023

The Singleton pattern is a software design pattern that restricts a class to have only one instance, and provides a global point of access to that instance. This pattern is often used in cases where a single instance of a class is required to coordinate actions across the system. In Salesforce, the Singleton pattern is useful for implementing shared state, as it allows multiple components to access and modify a single instance of an object.


The basic idea behind the Singleton pattern is to create a class that can only be instantiated once, and provides a global point of access to that instance. In Salesforce, this is achieved by making the class' constructor private, and providing a static method that returns the single instance of the class. This static method checks if an instance of the class has already been created, and returns it if it exists, or creates a new instance if it doesn't.

Here is an example of the Singleton pattern implemented in Apex:


public class Singleton {
  private static Singleton instance;
  private String sharedValue;

  private Singleton() {}

  public static Singleton getInstance() {
    if (instance == null) {
      instance = new Singleton();
    }
    return instance;
  }

  public void setSharedValue(String value) {
    this.sharedValue = value;
  }

  public String getSharedValue() {
    return this.sharedValue;
  }
}

In this example, the Singleton class has a private constructor, which prevents instances of the class from being created directly. The 'getInstance' method is a static method that returns the single instance of the class, creating a new instance if one doesn't already exist. The class also has a 'sharedValue' property, which can be used to store shared state that can be accessed by multiple components.

To use the Singleton class, a component can call the 'getInstance' method, which returns the single instance of the class. The component can then use the returned instance to access or modify the shared state.


Singleton singleton = Singleton.getInstance();
singleton.setSharedValue("Hello, World!");
String sharedValue = singleton.getSharedValue();

In conclusion, the Singleton pattern is a useful pattern for implementing shared state in Salesforce. By restricting a class to have only one instance and providing a global point of access to that instance, the Singleton pattern allows multiple components to access and modify a single instance of an object, providing a convenient and efficient way to coordinate actions across the system.

180 views1 comment

Recent Posts

See All

1 Comment


Sridhar NareshIT
Sridhar NareshIT
Sep 02, 2023

Easy to understand , Keep posting more blogs on Apex

Like
bottom of page