设计模式-责任链模式

 

China of Responsibility,职责链模式:使多个对象都有机会处理请求,从而避免请求的送发者和接收者之间的耦合关系

接触于开源网关项目soul

git地址:https://github.com/Dromara/soul

通过源码学习总结如下

1.插件化支持,插件采用责任链模式,顺序执行插件

2.热插拔采用zookeeper订阅机制刷新插件集合内部实现为map,通过排序转为list插件集

3.插件的具体实现一只半解,就不说了

其中收获最深的还是对责任链的理解

责任链执行器

private static class DefaultSoulPluginChain implements SoulPluginChain {

        private int index;

        private final List<SoulPlugin> plugins;

        /**
         * Instantiates a new Default soul plugin chain.
         *
         * @param plugins the plugins
         */
        DefaultSoulPluginChain(final List<SoulPlugin> plugins) {
            this.plugins = plugins;
        }

        /**
         * Delegate to the next {@code WebFilter} in the chain.
         *
         * @param exchange the current server exchange
         * @return {@code Mono<Void>} to indicate when request handling is complete
         */
        @Override
        public Mono<Void> execute(final ServerWebExchange exchange) {
            if (this.index < plugins.size()) {
                SoulPlugin plugin = plugins.get(this.index++);
                return plugin.execute(exchange, this);
            } else {
                return Mono.empty();
            }
        }
    }
}

责任链对象执行器

@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
    其他的业务源码就不贴了,doexcute调用子类具体插件的实现  
    return doExecute(exchange, chain, selectorZkDTO, rule);
}

 具体子类执行器

@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorZkDTO selector, final RuleZkDTO rule) {
    经过业务处理之后调用责任链执行器的excute继续
    chain.execute(exchange);
}

一个轮回之后,到责任链执行器开始下一个责任对象的执行

直到结束

其他开源框架也要责任链的具体实现

参考网址:https://www.cnblogs.com/lizo/p/7503862.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值