All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.lulihu.designPattern.chain.ResponsibilityChainHandler Maven / Gradle / Ivy

package net.lulihu.designPattern.chain;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 责任链处理程序
 * 

* 使用方式代码如下: *

 * public static class B extends AbstractHandlerResponsibilityChainResolver {
 *
 *  public boolean support(AtomicInteger data) {
 *   return true;
 *  }
 *
 *  public boolean resolve(AtomicInteger data) throws Exception {
 *   System.out.println(data.intValue());
 *   data.incrementAndGet();
 *   return true;
 *  }
 * }
 *
 *  public static void main(String[] args) {
 *   ResponsibilityChainHandler chainHandler = new ResponsibilityChainHandler<>();
 *   chainHandler.addHandler(new B()).addHandler(new B()).addHandler(new B());
 *   chainHandler.handler(new AtomicInteger(1));
 *   }
 * 
* * @param */ @Slf4j public class ResponsibilityChainHandler { private List> chainResolvers; private ResponsibilityChainEventHandler eventHandler; /** * 实例化时必须指定实际类型,因为该对象类型为动态设置无法通过反射获取类型 */ public ResponsibilityChainHandler() { this.chainResolvers = new ArrayList<>(); } /** * 添加下个处理对象 * * @param chain 下个处理对象 */ public ResponsibilityChainHandler addHandler(AbstractHandlerResponsibilityChainResolver chain) { this.chainResolvers.add(chain); return this; } /** * 设置异常处理器 * * @param eventHandler 事件处理器 */ public void setEventHandler(ResponsibilityChainEventHandler eventHandler) { this.eventHandler = eventHandler; } /** * 开始处理程序 * * @param data 参数 */ public void handler(T data) { if (null != this.eventHandler) { // 事件执行前回调 boolean beforeEvent = this.eventHandler.beforeEventHandler(data); if (!beforeEvent) return; } AbstractHandlerResponsibilityChainResolver resolver = null; try { // 执行事件 for (AbstractHandlerResponsibilityChainResolver chainResolver : chainResolvers) { data = (resolver = chainResolver).handlerEvent(data); } } catch (ChainDisconnectedException ignored) { // 忽略 } catch (Exception e) { // 事件异常回调 if (null != this.eventHandler) this.eventHandler.onEventExceptionHandler( resolver != null ? resolver.getName() : null, data, e); else e.printStackTrace(); return; } // 事件结束回调 if (null != this.eventHandler) this.eventHandler.afterEventHandler(data); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy