8.行为型 - 责任链模式 (Chain of Responsibility)

1.定义

  • 将多个对象连成一条“链”,请求沿着这条链传递,直到有对象处理该请求
  • 请求由哪个对象处理,是在运行时动态决定

2.UML类图

在这里插入图片描述

  • 角色说明
    AbstractHandler : 抽象处理者,声明请求处理的方法,并且持有下一个处理对象的引用
    ConcreteHandlerA : 具体处理者A,处理请求,若不能则将请求传递给下一节点
    ConcreteHandlerB : 具体处理者B

  • 要点说明
    抽象处理者持有下一个处理对象的引用,这个是“链”的保证;
    处理者对象要么处理请求,要么传递请求,不允许既处理又传递。

    请求被其中一个处理者处理:纯的责任链
    请求不被任何一个处理者处理:不纯的责任链

3.UML示例代码

/**
 * Copyright (C), 2016-2020
 * FileName: AbstractHandler
 * Author: wei.zheng
 * Date: 2019/12/11 20:40
 * Description: 抽象处理者
 */
public abstract class AbstractHandler {
    protected AbstractHandler nextHandler;

    public abstract void handleRequest(String condition);

    public AbstractHandler getNextHandler() {
        return nextHandler;
    }

    public void setNextHandler(AbstractHandler nextHandler) {
        this.nextHandler = nextHandler;
    }
}
/**
 * Copyright (C), 2016-2020
 * FileName: ConcreteHandlerAA
 * Author: wei.zheng
 * Date: 2019/12/11 21:02
 * Description: 具体解决者AA
 */
public class ConcreteHandlerAA extends AbstractHandler {

    private boolean canHandle(String condition) {
        if (condition.equals("ConcreteHandlerAA")) {
            return true;
        }

        return false;
    }

    @Override
    public void handleRequest(String condition) {
        if (canHandle(condition)) {
            System.out.println("ConcreteHandlerAA handle this condition");
        } else {
            nextHandler.handleRequest(condition);
        }
    }
}
/**
 * Copyright (C), 2016-2020
 * FileName: ConcreteHandlerBB
 * Author: wei.zheng
 * Date: 2019/12/11 21:15
 * Description: 具体解决者AA
 */
public class ConcreteHandlerBB extends AbstractHandler {

    private boolean canHandle(String condition) {
        if (condition.equals("ConcreteHandlerBB")) {
            return true;
        }

        return false;
    }

    @Override
    public void handleRequest(String condition) {
        if (canHandle(condition)) {
            System.out.println("ConcreteHandlerBB handle this condition");
        } else {
            nextHandler.handleRequest(condition);
        }
    }
}
/**
 * Copyright (C), 2016-2020
 * FileName: Client
 * Author: wei.zheng
 * Date: 2019/12/11 21:16
 * Description: 用户类
 */
public class Client {
    public static void main(String[] args) {
        ConcreteHandlerAA concreteHandlerAA = new ConcreteHandlerAA();

        ConcreteHandlerBB concreteHandlerBB = new ConcreteHandlerBB();

        concreteHandlerAA.setNextHandler(concreteHandlerBB);

        concreteHandlerBB.setNextHandler(concreteHandlerAA);

        concreteHandlerAA.handleRequest("ConcreteHandlerBB");
    }
}
输出结果:

2019-12-11 21:22:15.900 6226-6226/com.example.iterator I/System.out: ConcreteHandlerBB handle this condition

4.总结

  • 优缺点
    优点: 请求与处理者之间的解耦
    缺点:若处理者过多,则遍历处理者的遍历会影响性能,慎用递归遍历
发布了37 篇原创文章 · 获赞 0 · 访问量 577

猜你喜欢

转载自blog.csdn.net/qq_37514242/article/details/103500280