Trigger factory implementation in Salesforce

These patterns provide an elegant way of coding triggers to avoid bad practices such as repetitive SOQL queries that can hit governor limits and multiple triggers over the same object. The patterns enforce a logical sequence to the trigger code and in turn help to keep code tidy and more maintainable. Keeping trigger logic for each object in a single place avoids problems where multiple triggers are in contention with each other and makes it easier to debug. Enforcing up front caching of data within a trigger keeps the trigger 'bulkified' and avoids those nasty 'too many SOQL queries'.

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);
}

Cheers!!!

2 comments:

  1. private static ITrigger getHandler(Schema.sObjectType soType)
    why you define 2 names like ITrigger getHandler in same method

    ReplyDelete
    Replies
    1. I haven't defined it twice. Please mention the line numbers.

      Delete