设计模式: 责任链模式

这个博客讨论了一个抽象类`XxxxxHandlerChain`,它用于处理链式结构中的节点添加和移除。`appendLast`方法用于在链式结构的末尾添加新节点,而`remove`方法实现了在链中移除指定类型的节点,允许删除中间节点。`handle`方法处理消息传递,先由当前节点尝试消费,然后交给下一个节点,如果所有节点都无法消费,则调用`consumeAgain`方法。
摘要由CSDN通过智能技术生成
public abstract class XxxxxHandlerChain<Model> {

    /**
     * 当前节点所持有的小一份节点
     */
    private volatile XxxxxHandlerChain<Model> next;

    /**
     * 添加一个新的节点到当前链式结构的末尾
     * !!只允许 一种类型的链 在链表上
     *
     * @param newChain 新的节点
     * @return 返回新的节点
     */
    public XxxxxHandlerChain<Model> appendLast(XxxxxHandlerChain<Model> newChain) {
        if (this == newChain || this.getClass() == newChain.getClass()) {
            return this;
        }

        synchronized (this) {
            if (next == null) {
                next = newChain;
                return newChain;
            }
            // 否则让下一个节点进行新节点的添加,把责任让后推
            return next.appendLast(newChain);
        }
    }

    /**
     * 移除某节点时,如果其具有后续的节点,则把后续节点接到当节点上;实现可以移除中间某个节点
     *
     * @param clx 待移除节点的Class信息
     * @return 是否移除成功
     */
    public synchronized boolean remove(Class<? extends XxxxxHandlerChain<Model>> clx) {
        // 自己不能移除自己,因为自己未持有上一个链接的引用
        if (this.getClass() == clx) {
            return false;
        }
        synchronized (this) {
            if (next == null) {
                // 当前无下一个节点存在,无法判断
                return false;
            }
            if (next.getClass() == clx) {
                //如果下一个节点相等  把此节点的下一个节点的下一个节点 等于此节点的下一个节点就移除了下一个
                next = next.next;
                return true;
            }
            return remove(clx);
        }

    }

    /**
     * 优先自己消费,如果自己未消费;则给next消费
     * 若:next=null 或 next 未消费,则回调{@link #consumeAgain(ConnectorHandler, Object)} 尝试再次消费
     *
     * @param handler ClientHandler
     * @param model   Model
     * @return True consume 消费 或 consumeAgain 消费
     */
    synchronized boolean handle(ConnectorHandler handler, Model model) {
        XxxxxHandlerChain<Model> next = this.next;
        // 自己消费
        if (consume(handler, model)) {
            return true;
        }
        boolean nextSucceed = next != null && next.handle(handler, model);
        if (nextSucceed) {
            return true;
        }
        return consumeAgain(handler, model);
        //return nextSucceed || consumeAgain(handler, model);
    }

    /**
     * 消费
     *
     * @param handler
     * @param model
     * @return
     */
    public abstract boolean consume(ConnectorHandler handler, Model model);

    public boolean consumeAgain(ConnectorHandler handler, Model model) {
        return false;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值