Pipeline 责任链

public class Main {
    public static void main(String[] args) {
        Pipeline p = new Pipeline();
        p.addLast(new Handler1());
        p.addLast(new Handler2());
        p.requestProcess("开始了....");
    }
}

打印:
这是头部
Handler1
Handler2
public class Pipeline {

    public HandlerChainContext context = new HandlerChainContext(new AbstractHandler() {
        @Override
        void doHandler(HandlerChainContext context, Object arg0) {
            System.out.println("这是头部");
            context.runNext(arg0);
        }
    });


    // 添加责任链
    public void addLast(AbstractHandler handler) {
        HandlerChainContext current = context;
        while (current.next != null) {
            current = current.next;             
        }   //最核心也就这句 找到最后 添加下一个
        current.next = new HandlerChainContext(handler);
    }

    // 开始调用
    public void requestProcess(Object arg0) {
        context.handler(arg0);
    }
}

public abstract class AbstractHandler {
    abstract void doHandler(HandlerChainContext context, Object arg0);
}

public class Handler1 extends AbstractHandler {

    @Override
    void doHandler(HandlerChainContext context, Object arg0) {
        System.out.println("Handler1");
        context.runNext(arg0);
    }
}
public class Handler2 extends AbstractHandler {

    @Override
    void doHandler(HandlerChainContext context, Object arg0) {
        System.out.println("Handler2");
        context.runNext(arg0);
    }
}
public class HandlerChainContext {
    HandlerChainContext next;// 持有下一个节点

    AbstractHandler handler;

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

    void handler(Object arg0) {
        this.handler.doHandler(this, arg0);
    }

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

posted @ 2022-09-27 14:37  z_先生  阅读(34)  评论(0编辑  收藏  举报