Trigger factory implementation in Salesforce

Trigger factory implementation in Salesforce

The patterns in Salesforce triggers help us to avoid bad practices such as repetitive SOQL queries or too many DML statements that can hit governor limits and also avoids multiple triggers over the same object. These patterns helps us to have a logical sequence to the trigger code and in turn helps us to keep the code neat and easy for maintenance. 

Use the below link for Trigger factory implementation in Salesforce

http://developer.force.com/cookbook/recipe/trigger-pattern-for-tidy-streamlined-bulkified-triggers

Sample Trigger pattern for Opportunity Object:

ITrigger Interface:

public interface ITrigger {
 void bulkBefore();
 void bulkAfter();
}

OpportunityTriggerHandler Apex Class:
public with sharing class OpportunityTriggerHandler implements ITrigger {  
 public OpportunityTriggerHandler() {
 }
 
 public void bulkBefore() {
  if(trigger.isInsert) {
   //Here we will call before insert actions
  } else if(trigger.isUpdate) {
   //Here we will call before update actions
  } else if(trigger.isDelete) {
   //Here we will call before delete actions
  } else if(trigger.isUndelete) {
   //Here we will call before undelete actions
  }
 }
 
 public void bulkAfter() {
  if(trigger.isInsert) {
   //Here we will call after insert actions
  } else if(trigger.isUpdate) {
   //Here we will call after update actions
  } else if(trigger.isDelete) {
   //Here we will call after delete actions
  } else if(trigger.isUndelete) {
   //Here we will call after undelete actions
  }
 }  
}

TriggerFactory Apex Class:

public with sharing class TriggerFactory {
 public static void createHandler(Schema.sObjectType soType) {
  ITrigger handler = getHandler(soType);
  
  if(handler == null) {
   throw new TriggerException('No Trigger Handler registered for Object Type: ' + soType);
  }
  
  // Execute the handler to fulfil the trigger
  execute(handler);
 }
 private static void execute(ITrigger handler) {
  // Before Trigger
  if(Trigger.isBefore) {
   handler.bulkBefore();
  }
  else {
   handler.bulkAfter();
  }
 }
 
 private static ITrigger getHandler(Schema.sObjectType soType) {
  if(soType == Opportunity.sObjectType) {
   return new OpportunityTriggerHandler();
  }
  
  return null;
 }
}

Opportunity Trigger:

trigger AccountTrigger on Opportunity(after delete, after insert, after update, before delete, before insert, before update) {

TriggerFactory.createHandler( Opportunity.sObjectType );

}

Leave a Reply