设计模式-行为型模式-职责链模式

在软件系统运行时,对象并不是孤立存在的,它们可以通过相互通信协作完成某些功能,一个对象在运行时也将影响到其他对象的运行。行为型模式(Behavioral Pattern)关注系统中对象之间的交互,研究系统在运行时对象之间的相互通信与协作,进一步明确对象的职责。行为型模式不仅仅关注类和对象本身,还重点关注它们之间的相互作用和职责划分。

职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。[DP]

复制代码
// 抽象处理者类
abstract class Handler {
    protected Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    // 处理请求的方法,由具体处理者实现
    public abstract void handleRequest(int request);
}

// 具体处理者A
class ConcreteHandlerA extends Handler {
    @Override
    public void handleRequest(int request) {
        if (request >= 0 && request < 10) {
            System.out.println("处理者A处理请求:" + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

// 具体处理者B
class ConcreteHandlerB extends Handler {
    @Override
    public void handleRequest(int request) {
        if (request >= 10 && request < 20) {
            System.out.println("处理者B处理请求:" + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

// 具体处理者C
class ConcreteHandlerC extends Handler {
    @Override
    public void handleRequest(int request) {
        if (request >= 20) {
            System.out.println("处理者C处理请求:" + request);
        }
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Handler handlerA = new ConcreteHandlerA();
        Handler handlerB = new ConcreteHandlerB();
        Handler handlerC = new ConcreteHandlerC();

        // 设置职责链
        handlerA.setSuccessor(handlerB);
        handlerB.setSuccessor(handlerC);

        // 客户端发送请求
        handlerA.handleRequest(5);
        handlerA.handleRequest(15);
        handlerA.handleRequest(25);
    }
}
相关推荐
云徒川1 小时前
【设计模式】过滤器模式
windows·python·设计模式
找了一圈尾巴11 小时前
设计模式(结构性)-代理模式
设计模式·代理模式
渊渟岳11 小时前
掌握设计模式--模板方法模式
设计模式
程序员JerrySUN1 天前
设计模式 Day 2:工厂方法模式(Factory Method Pattern)详解
设计模式·工厂方法模式
牵牛老人1 天前
C++设计模式-迭代器模式:从基本介绍,内部原理、应用场景、使用方法,常见问题和解决方案进行深度解析
c++·设计模式·迭代器模式
诺亚凹凸曼1 天前
23种设计模式-结构型模式-组合
设计模式
诺亚凹凸曼1 天前
23种设计模式-结构型模式-桥接器
android·java·设计模式
却尘1 天前
跨域资源共享(CORS)完全指南:从同源策略到解决方案 (1)
前端·设计模式
coderzpw2 天前
设计模式中的“万能转换器”——适配器模式
设计模式·适配器模式
三金C_C2 天前
单例模式解析
单例模式·设计模式·线程锁