function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ShwetaShweta 

How to stop creation of instances .

Hi,
I was wondering,  can we stop creating instances while there are instances already running of the apex class?

Thanks
Shweta.
Best Answer chosen by Shweta
Kapil_KhandelwalKapil_Khandelwal
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;
    }
}

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