君临-行者无界

导航

责任链模式

  实现责任链模式有4个要素,处理器抽象类、处理器实现类、保存处理器的信息、处理执行

  常见责任链的实现方式有两种,一种是数组轮询:例如过滤器filter的实现,一种是链表传递:例如netty实现

  两种形式伪代码实现

 

  下面给出一个链式调用的demo

package com.example.test;


/**
 * 链表形式调用,维护链和链的触发
 */
public class PipelineDemo {

    //链表头部,什么也不做,用作链表的触发执行
    private HandlerChainContext head = new HandlerChainContext((handerChainContext,obj) ->{
        handerChainContext.runNext(obj);
    });

    public void addLast(AbstractHandler handler){
        HandlerChainContext handlerChainContext = head;
        while (handlerChainContext.next!=null){
            handlerChainContext = handlerChainContext.next;
        }
        handlerChainContext.next = new HandlerChainContext(handler);

    }


    public void process(Object obj){
        this.head.handler(obj);
    }

    public static void main(String[] args) {
        PipelineDemo pipelineDemo = new PipelineDemo();
        pipelineDemo.addLast(new Hander1());
        pipelineDemo.addLast(new Hander2());
        pipelineDemo.addLast(new Hander2());
        pipelineDemo.addLast(new Hander1());
        pipelineDemo.process("开始了,");
    }



}

/**
 * 抽象接口
 */
interface AbstractHandler{

    void handler(HandlerChainContext handlerChainContext,Object obj);

}

/**
 * 具体实现
 */
class Hander1 implements AbstractHandler{
    @Override
    public void handler(HandlerChainContext handlerChainContext, Object obj) {
        obj = obj.toString() + "hand1处理完毕~~~";
        System.out.println(obj);
        handlerChainContext.runNext(obj);
    }
}


class Hander2 implements AbstractHandler{
    @Override
    public void handler(HandlerChainContext handlerChainContext, Object obj) {
        obj = obj.toString() + "hand2处理完毕~~~";
        System.out.println(obj);
        handlerChainContext.runNext(obj);
    }
}

/**
 * 链表上下文 存储链信息
 */
class HandlerChainContext{

    HandlerChainContext next;

    private AbstractHandler handler;

    public HandlerChainContext(AbstractHandler handler){
        this.handler = handler;
    }

    public void handler(Object obj){
        this.handler.handler(this,obj);
    }

    void runNext(Object obj){
        if(this.next!=null){
            this.next.handler(obj);
        }
    }


}

 

posted on 2019-03-23 22:11  请叫我西毒  阅读(729)  评论(0编辑  收藏  举报