Singleton Design Pattern in Apex
- girish kotgire
- Dec 4, 2022
- 1 min read
1] Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists per transaction in apex.
2] It allows for only one instance of an object, but everyone has global access to that object.
3] Singleton class must provide a public access point to get the instance of the class for any transaction.
4] Singleton pattern can be used for logging and caching-related implementation.
Implement Singleton pattern in Apex:
1] Private Constructor: Create one private constructor to restrict the
instantiation of the apex class from other classes.
2] Private static variable: create a private static variable of the same class that is the only instance of the class.
3] public method getInstance(): Create one public static method that returns the instance of the class. getInstance method will only initiate an instance of a class if it does not exist
public with sharing class Singleton {
//private static instance of the class
private static Singleton instance = null;
//private constructor to avoid creating an instance
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
In this pattern, instance will only be instantiated when we call the getInstance() method. This will reduce the effort to load large resources at the time of initialization. Like below code
Singleton instance = Singleton.getInstance();
Comentarios