行为型(四) - 责任链模式

一、概念

责任链模式(Chain Of Responsibility Pattern):将请求的发送和接收解耦,让多个接收对象都有机会处理这个请求。将这些接收对象串成一条链,并沿着这条链传递这个请求,直到链上的某个接收对象能够处理它为止。

二、实现

具体的实现方式有两种,用链表存储处理器和用数组存储处理器。

  • 用链表存储处理器

1、问题处理抽象类

public abstract class QuestionHandler {
    private QuestionHandler nextHandler;
    
    public void setNextHandler(QuestionHandler nextHandler) {
        this.nextHandler = nextHandler;
    }

    //使用模板模式将该方法设置为final,这样避免子类实现的时候忘记调用nextHandler.handleQuestion();
    public final void handleQuestion() {
        boolean isHandled = doHandle();
        if (!isHandled && nextHandler != null) {
            nextHandler.handleQuestion();
        }
    }
  
    public abstract boolean doHandle();
}

2、问题处理实现类

public class QuestionHandlerA extends QuestionHandler {
    @Override
    public boolean doHandle() {
        System.out.println("QuestionHandlerA - doHandle");
        return false;
    }
}

public class QuestionHandlerB extends QuestionHandler {
    @Override
    public boolean doHandle() {
        System.out.println("QuestionHandlerB - doHandle");
        return true;
    }
}

public class QuestionHandlerC extends QuestionHandler {
    @Override
    public boolean doHandle() {
        System.out.println("QuestionHandlerC - doHandle");
        return false;
    }
}

3、测试类

public class Client {
    public static void main(String[] args) {
        QuestionHandlerA handlerA = new QuestionHandlerA();
        QuestionHandlerB handlerB = new QuestionHandlerB();
        QuestionHandlerC handlerC = new QuestionHandlerC();

        handlerA.setNextHandler(handlerB);
        handlerB.setNextHandler(handlerC);
        handlerA.handleQuestion();
    }
}
  • 用数组存储处理器

1、在上面代码的基础上加一个QuestionHandlerChain类来保存所有处理器。

public class QuestionHandlerChain {
    List<QuestionHandler> handlers = new ArrayList<>();

    public void addQuestionHandler(QuestionHandler handler) {
        if (handler != null && !handlers.contains(handler)) {
            handlers.add(handler);
        }
    }

    public void startHandleQuestion() {
        for (QuestionHandler handler : handlers) {
            boolean isHandled = handler.doHandle();
            if (isHandled){
                break;
            }      
        }
    }
}

2、测试类

public class Client {
    public static void main(String[] args) {
        QuestionHandlerA handlerA = new QuestionHandlerA();
        QuestionHandlerB handlerB = new QuestionHandlerB();
        QuestionHandlerC handlerC = new QuestionHandlerC();

        QuestionHandlerChain chain = new QuestionHandlerChain();
        chain.addQuestionHandler(handlerA);
        chain.addQuestionHandler(handlerB);
        chain.addQuestionHandler(handlerC);
        chain.startHandleQuestion();
    }
}

3、运行结果
责任链模式结果.png

你可能感兴趣的:(设计模式,责任链模式,java,开发语言)