需求:Trigger代码里面,肯定是不建议写具体的逻辑代码,那么我们就需要一个TriggerHander的示例
下面是一个所有Object都可以继承的TriggerHander的接口代码
public interface TriggerHandler {
void beforeInsert(List<SObject> newRecords);
void beforeUpdate(List<SObject> oldRecords, List<SObject> newRecords, Map<ID, SObject> oldRecordMap, Map<ID, SObject> newRecordMap);
void beforeDelete(List<SObject> oldRecords, Map<ID, SObject> oldRecordMap);
void afterInsert(List<SObject> newRecords, Map<ID, SObject> newRecordMap);
void afterUpdate(List<SObject> oldRecords, List<SObject> newRecords, Map<ID, SObject> oldRecordMap, Map<ID, SObject> newRecordMap);
void afterDelete(List<SObject> oldRecords, Map<ID, SObject> oldRecordMap);
void afterUndelete(List<SObject> newRecords, Map<ID, SObject> newRecordMap);
}
下面是一个Account的TriggerHandler继承TriggerHandler
在下面的示例代码里面,大家可能注意到了AccountTriggerHelper的存在。
这个我们后面会讲到,我们把具体的逻辑代码,可以全部放到这个AccountTriggerHelper 里面。
public without sharing class AccountTriggerHandler implements TriggerHandler {
private boolean triggerIsExecuting;
private integer triggerSize;
public AccountTriggerHelper helper;
public AccountTriggerHandler(boolean triggerIsExecuting, integer triggerSize) {
this.triggerIsExecuting = triggerIsExecuting;
this.triggerSize = triggerSize;
this.helper = new AccountTriggerHelper();
}
public void beforeInsert(List<Account> newAccounts) {
// helper.doTask1();
// helper.doTask2();
}
public void beforeUpdate(List<Account> oldAccounts, List<Account> newAccounts, Map<ID, SObject> oldAccountMap, Map<ID, SObject> newAccountMap) {
// helper.doTask3();
// helper.doTask4();
}
public void beforeDelete(List<Account> oldAccounts, Map<ID, SObject> oldAccountMap) {
// helper.doTask5();
// helper.doTask1();
}
public void afterInsert(List<Account> newAccounts, Map<ID, SObject> newAccountMap) {
// helper.doTask2();
// helper.doTask3();
}
public void afterUpdate(List<Account> oldAccounts, List<Account> newAccounts, Map<ID, SObject> oldAccountMap, Map<ID, SObject> newAccountMap) {
// helper.doTask4();
// helper.doTask5();
}
public void afterDelete(List<Account> oldAccounts, Map<ID, SObject> oldAccountMap) {
// helper.doTask3();
// helper.doTask1();
}
public void afterUndelete(List<Account> newAccounts, Map<ID, SObject> newAccountMap) {
// helper.doTask4();
// helper.doTask2();
}
}
这里就是Helper的示例代码。我们可以把所有的任务都拆分开,分别写在不同的方法里面。方便AccountTriggerHandler调用。
public without sharing class AccountTriggerHelper {
public AccountTriggerHelper() {
System.debug('Inside AccountTriggerHelper Constructor');
}
public void doTask1() {
System.debug('Inside Task 1');
}
public void doTask2() {
System.debug('Inside Task 2');
}
public void doTask3() {
System.debug('Inside Task 3');
}
public void doTask4() {
System.debug('Inside Task 4');
}
public void doTask5() {
System.debug('Inside Task 5');
}
}
本文参考到了下面的链接文章。
https://www.salesforceben.com/the-salesforce-trigger-handler-framework/