JAVA编程艺术之责任链模式(一)

JAVA编程艺术之责任链模式

在很多中间件,大家看源码都能看到代码的优雅设计,其中常用的一种设计模式责任链模式,在我们系统架构和项目中会经常用到这种设计模式;大家平时看的书籍设计模式之禅对这种设计模式也有阐述;其实简单来讲责任链模式就是多个对象,每个对象保持对下一个对象的引用从而处理一个具有链式场景的,对调用者隐藏具体实现的一种设计模式;具体实现方式主要有模板责任链模式、策略责任链模式和函数式责任链模式;下面的介绍主要讲一下这种具体实现的思路


(一)模板责任链模式

采用继承,对象实现和链式调用器提供模板方法,由具体业务对象去实现模板方法

实现思路

链式处理加载总调度器,通过加载注解TaskFilters的bean,将多个需要串联的对象放在集合对象里面

public class TaskFrameProcessor extends InitDestroyAnnotationBeanPostProcessor implements ApplicationContextAware {

    public static final Logger logger = LoggerFactory.getLogger(TaskFrameProcessor.class);

    private ApplicationContext applicationContext;

    /**
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        try {
            if (bean instanceof BaseTask) {
                this.processTaskChain((BaseTask) bean, beanName);
            }
        } catch (Exception e) {
            throw new BeanInitializationException("TaskFrameProcessor.processTaskChain exception" + beanName, e);
        }
        return bean;
    }

    /**
     * @param baseTask
     * @param beanName
     * @throws Exception
     */
    private void processTaskChain(BaseTask baseTask, String beanName) throws Exception {
        Class<?> clazz = this.getBeanClass(baseTask);
        TaskFilters anno = null;
        while (null == anno && clazz != null) {
            anno = clazz.getAnnotation(TaskFilters.class);
            clazz = clazz.getSuperclass();
        }
        if (null == anno) {
            logger.error("TaskFrameProcessor.processTaskChain.taskFilters is blank beanName{}", beanName);
            return;
        }
        List<BaseFilter> filters = Lists.newArrayList();
        List<String> taskFilters = Lists.newArrayList(Splitter.on(",").trimResults().split(anno.value()));
        for (String filter : taskFilters) {
            BaseFilter baseFilter = (BaseFilter) this.applicationContext.getBean(filter);
            if (null != baseFilter) {
                filters.add(baseFilter);
            }
        }
        baseTask.setFilters(filters);
    }

    /**
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * @param bean
     * @return
     * @throws Exception
     */
    private Class<?> getBeanClass(Object bean) throws Exception {
        Class clazz;
        if (AopUtils.isJdkDynamicProxy(bean)) {
            clazz = ((Advised) bean).getTargetSource().getTarget().getClass();
        } else {
            clazz = bean.getClass();
        }
        return clazz;
    }
}

多个对象链式调度任务继承BaseTask模板,可以重写调用方法前和调用方法后的一些业务逻辑处理

public abstract class BaseTask<RQ extends BaseRequest, RS extends BaseResponse> {

    @Setter
    @Getter
    private List<BaseFilter<RQ, RS>> filters;

    /**
     * @param request
     * @param response
     * @throws Exception
     */
    protected abstract void beforeExecute(RQ request, RS response) throws Exception;

    /**
     * @param request
     * @param response
     * @throws Exception
     */
    protected abstract void afterExecute(RQ request, RS response) throws Exception;

    public void execute(RQ request, RS response) {
        try {
            this.beforeExecute(request, response);
            Assert.notEmpty(filters, "processTask.filters must not empty");
            for (BaseFilter filter : filters) {
                boolean result = filter.execute(request, response);
                if (!result) {
                    break;
                }
            }
            this.afterExecute(request, response);
        } catch (Exception e) {

        }
    }
}

对象实现具体业务逻辑继承BaseFilter模板方法,实现dealObject方法

public abstract class BaseFilter<RQ extends BaseRequest, RS extends BaseResponse> implements Cloneable {


    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public abstract boolean dealObject(RQ request, RS response) throws Exception;

    public boolean execute(RQ request, RS response) {
        try {
            boolean result = this.dealObject(request, response);
            return result;
        } catch (Exception e) {

        }
        return true;
    }

}

调用者只需要调用ExampleTask.excute(request,response);

@TaskFilters("exampleTask.stepOneFilter,exampleTask.stepTwoFilter")
public class ExampleTask extends BaseTask<ERequest, EResponse> {


    @Override
    protected void beforeExecute(ERequest request, EResponse response) throws Exception {

    }

    @Override
    protected void afterExecute(ERequest request, EResponse response) throws Exception {

    }
}

(二)策略责任链模式

用聚合,将处理节点和调度器分开

实现思路

处理链总调度器

public abstract class ProcessorChain<T> {

    public List<T> chainList = Lists.newArrayList();

    public <P extends ProcessorChain<T>> ProcessorChain<T> add(T t) {
        chainList.add(t);
        return this;
    }

    public void process(ContextAware contextAware) {
        if (CollectionUtils.isEmpty(chainList)) {
            defaultHandlerCombination();
        }
        this.execute(contextAware);

    }

    /**
     * @param contextAware
     */
    public abstract void execute(ContextAware contextAware);

    /**
     *
     */
    public abstract void defaultHandlerCombination();
}

链式对象需要实现的接口,具体业务逻辑实现doHandler就可以了,toSupport用来判断该对象调用条件

public interface FilterHandler {

    void doHandler(ContextAware contextAware);

    boolean toSupport(ContextAware contextAware);
}

调用者调用execute方法就可以了

@Component
public class ExampleProcessChain extends ProcessorChain<FilterHandler> {

    @Resource
    private ExampleFilterHandler exampleFilterHandler;

    @Override
    public void execute(ContextAware contextAware) {
        for (FilterHandler filterHandler : this.chainList) {
            if (filterHandler.toSupport(contextAware)) {
                filterHandler.doHandler(contextAware);
            }
        }
    }

    @Override
    public void defaultHandlerCombination() {
        //TODO handler combination
        this.add(exampleFilterHandler);
    }
}

(三)函数式责任链模式

函数式编程不同于oop思想,比较难理解

实现思路

函数,具体业务逻辑处理

public interface BizFunc<T extends FuncName> {

    BaseResponse apply(T apiName, BaseRequest req, Object[] args);
}

输入一个函数,返回一个增强函数,创建对象引用

public interface BizFuncFactory extends FuncFactory {

    BizFunc create(BizFunc next);
}

模板方法,通过create方法创建对象引用关系

public abstract class AbstractFuncFactory implements BizFuncFactory {

    @Override
    public BizFunc create(BizFunc next) {
        return new BizFunc() {
            @Override
            public BaseResponse apply(FuncName apiName, BaseRequest req, Object[] args) {
                return AbstractFuncFactory.this.apply(next, apiName, req, args);
            }
        };
    }

    protected abstract BaseResponse apply(BizFunc next, FuncName funcName, BaseRequest req, Object[] args);
}

每个实现模板方法的对象通过next.apply方法调用下一个引用对象

public class ExampleFuncFactory extends AbstractFuncFactory {

    @Override
    protected BaseResponse apply(BizFunc next, FuncName funcName, BaseRequest req, Object[] args) {
        try {
            //链式调用
            next.apply(funcName, req, args);
        } catch (Exception e) {

        }
        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值