Author - StudySection Post Views - 198 views
Apex

Apex Design Patterns – Singleton

Introduction

While implementing any code, sometimes we need to create an object of a class but we want to initiate it only once means we initiate an object once for the lifetime of its execution context.

Why do we need the singleton pattern?

  1. Singleton pattern unable us to use the facility of global variables. Since apex does not support global variables but with the help of a singleton pattern, we can achieve it.
  2. Singleton patterns also help us to govern the apex limits because we are not executing the same code again and again.

Problem
Sometimes a developer writes code that needs to initiate an object of a class again and again in a loop. It will result in inefficient, low-performing code, as well as the potential for governor limitations to be exceeded.

For example:
Public class Abc{
for(Account eachRecord : [SELECT Id, Name FROM Account]){
Xyz obj = new Xyz();
}
}
Public class Xyz{
public String id {get;private set;}
public Xyz(){
id = Account.sObjectType.getDescribe().getRecordTypeInfosByName().get(‘test’).getRecordTypeId();
}
}

This will cause a repeated execution of the sObject getDescribe() method, resulting in a breach of the total number of described governor limits if the code operates against more than 100 records.

Solution
To resolve this problem we need to implement the Singleton pattern in Apex, the class must instantiate only a single instance and be globally accessible. It is implemented by:

  • Creating a class that has a method that creates a new instance of the class if there is no existing instance.
  • If there is an instance that is already there then it will simply return a reference to that object

The Singleton pattern is used to return the record type using describe within the execution in the following code:
Public class Abc{
for(Account eachRecord : [SELECT Id, Name FROM Account]){
// get the record type using the singleton class
Id rt = Xyz.getInstance();
}
}
Public class Xyz{
private static Id rt = null {get; set;} // the id of the record type
private Xyz(){
rt = Account.sObjectType.getDescribe()
.getRecordTypeInfosByName().get(‘test’).getRecordTypeId();
}
public static Id getInstance(){
if(rt == null) Xyz obj = new Xyz();
return rt;
}
}

If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.

Leave a Reply

Your email address will not be published.