/** * Triggers 源码 * 本质是通过bind方法将对应的action和hanler 绑定对应的事件类型 * 然后通过manage 方法执行对应的业务逻辑 */ publicclassTriggers{ /** * Enum representing each of before/after CRUD events on Sobjects */ publicenumEvt{ afterdelete, afterinsert, afterundelete, afterupdate, beforedelete, beforeinsert, beforeupdate } /** * Simplistic handler to implement on any of the event. It doesn't requires or enforces any patter except the * method name to be "handle()", a developer is free to use any Trigger context variable or reuse any other * apex class here. */ publicinterfaceHandler{ voidhandle(); } // Internal mapping of handlers Map<String, List<Handler>> eventHandlerMapping = new Map<String, List<Handler>>(); /** * Core API to bind handlers with events */ public Triggers bind(Evt event, Handler eh){ List<Handler> handlers = eventHandlerMapping.get(event.name()); if (handlers == null) { handlers = new List<Handler>(); eventHandlerMapping.put(event.name(), handlers); } handlers.add(eh); returnthis; } /** * Invokes correct handlers as per the context of trigger and available registered handlers */ publicvoidmanage(){ Evt ev = null; if(Trigger.isInsert && Trigger.isBefore){ ev = Evt.beforeinsert; } elseif(Trigger.isInsert && Trigger.isAfter){ ev = Evt.afterinsert; } elseif(Trigger.isUpdate && Trigger.isBefore){ ev = Evt.beforeupdate; } elseif(Trigger.isUpdate && Trigger.isAfter){ ev = Evt.afterupdate; } elseif(Trigger.isDelete && Trigger.isBefore){ ev = Evt.beforedelete; } elseif(Trigger.isDelete && Trigger.isAfter){ ev = Evt.afterdelete; } elseif(Trigger.isundelete){ ev = Evt.afterundelete; } List<Handler> handlers = eventHandlerMapping.get(ev.name()); if (handlers != null && !handlers.isEmpty()) { for (Handler h : handlers) { h.handle(); } } } }