Hi Shweta, The Singleton pattern attempts to solve the issue where you are repeatedly using an object instance but only wish to instantiate it once within a single transaction context.
The following code sample demonstrates an implementation of the Singleton pattern to return a record type describe within a trigger:
trigger AccountTrigger on Account (before insert, before update) {
for(Account record : Trigger.new){
// Instantiate the record type using the singleton class
AccountFooRecordType rt = AccountFooRecordType.getInstance();
....
}
}
public class AccountFooRecordType {
// private static variable referencing the class
private static AccountFooRecordType instance = null;
public String id {get;private set;} // the id of the record type
// The constructor is private and initializes the id of the record type
private AccountFooRecordType(){
id = Account.sObjectType.getDescribe()
.getRecordTypeInfosByName().get('Foo').getRecordTypeId();
}
// a static method that returns the instance of the record type
public static AccountFooRecordType getInstance(){
// lazy load the record type - only initialize if it doesn't already exist
if(instance == null) instance = new AccountFooRecordType();
return instance;
}
}
The Singleton pattern attempts to solve the issue where you are repeatedly using an object instance but only wish to instantiate it once within a single transaction context.
The following code sample demonstrates an implementation of the Singleton pattern to return a record type describe within a trigger:
Hope my answer helps you.
Kapil Khandelwal
AppPerfect Corp.
salesforce@appperfect.com
408-252-4100
http://www.appperfect.com/services/salesforce/
Salesforce Development & Operations Experts