Java责任链模式(Chain of Responsibility Pattern)详解

说明:

责任链模式(Chain of Responsibility Pattern)是一种行为型设计模式,它允许多个对象按照顺序处理请求,每个对象都可以选择处理请求或将其传递给链中的下一个对象。

在责任链模式中,有以下主要角色:

Handler(处理者):它定义了一个处理请求的接口,并持有下一个处理者的引用。处理者可以选择自己处理请求,也可以将请求传递给下一个处理者。

ConcreteHandler(具体处理者):它实现了处理请求的方法。如果可以处理请求,就直接处理;否则,将请求传递给下一个处理者。

在责任链模式中,请求沿着处理者链向下传递,直到有一个处理者可以处理该请求为止。每个处理者都有机会处理请求,但具体由哪个处理者处理取决于其具体实现。

下面是责任链模式的主要特点和应用场景:

特点:

动态组合:可以动态地组合和修改处理者的顺序和个数。

解耦请求发送者和接收者:请求发送者无需知道请求将由哪个处理者处理,处理者也无需知道请求的发送者。

应用场景:

当有多个对象可以处理同一请求,但具体由哪个对象处理取决于运行时的条件时,可以使用责任链模式。

当希望将请求的发送者和接收者解耦,使得请求发送者不需要知道请求的处理细节时,可以使用责任链模式。

当希望动态组合处理者并灵活地添加、修改或删除处理者时,可以使用责任链模式。

当有一个处理请求的对象集合,但不确定哪个对象最终会处理请求时,可以使用责任链模式。

责任链模式在实际应用中非常常见,例如:Java中的异常处理机制、Web请求的过滤器链、日志记录器链等。

翻译:

The Chain of Responsibility Pattern is a behavioral design pattern that allows multiple objects to sequentially handle a request. Each object in the chain can choose to handle the request or pass it to the next object in the chain.

In the Chain of Responsibility Pattern, there are the following main roles:

Handler: It defines an interface for handling requests and holds a reference to the next handler in the chain. The handler can choose to handle the request itself or pass it to the next handler.

ConcreteHandler: It implements the handling method. If it can handle the request, it handles it directly; otherwise, it passes the request to the next handler in the chain.

In the Chain of Responsibility Pattern, the request is passed down the chain of handlers until one of the handlers can handle it. Each handler has the opportunity to handle the request, but the specific handler depends on its implementation.

Here are the main characteristics and application scenarios of the Chain of Responsibility Pattern:

Characteristics:

Dynamic composition: Handlers can be dynamically composed and the order and number of handlers can be modified dynamically.

Decoupling of the request sender and receiver: The request sender does not need to know which handler will handle the request, and the handlers do not need to know the details of the request sender.

Application scenarios:

When multiple objects can handle the same request, but the specific object that handles it depends on runtime conditions, the Chain of Responsibility Pattern can be used.

When you want to decouple the request sender and receiver, so that the request sender does not need to know the details of request handling, the Chain of Responsibility Pattern can be used.

When you want to dynamically compose handlers and have flexibility in adding, modifying, or removing handlers, the Chain of Responsibility Pattern can be used.

When you have a collection of objects for handling requests, but you are not sure which object will ultimately handle the request, the Chain of Responsibility Pattern can be used.

The Chain of Responsibility Pattern is widely used in practical applications, such as the exception handling mechanism in Java, the filter chain in web requests, and the logger chain.

让我们以一个报销申请的审批流程为例来详细说明责任链模式的应用。

假设有一个报销系统,涉及多个层级的审批,包括员工、主管、部门经理和财务经理。当员工提交报销申请时,需要按照一定的规则和层级进行审批,直到最终决定是否批准报销。

首先,我们定义一个抽象处理者(Handler)接口,其中包含处理请求的方法和设置下一个处理者的方法:

public abstract class Handler {
    protected Handler nextHandler;

    public void setNextHandler(Handler nextHandler) {
        this.nextHandler = nextHandler;
    }

    public abstract void handleRequest(double amount);
}

然后,我们实现具体处理者(ConcreteHandler)类,分别代表员工、主管、部门经理和财务经理,并重写处理请求的方法:

public class Employee extends Handler {
    public void handleRequest(double amount) {
        if (amount <= 100) {
            System.out.println("Employee approves the reimbursement.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(amount);
        }
    }
}

public class Supervisor extends Handler {
    public void handleRequest(double amount) {
        if (amount <= 500) {
            System.out.println("Supervisor approves the reimbursement.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(amount);
        }
    }
}

public class DepartmentManager extends Handler {
    public void handleRequest(double amount) {
        if (amount <= 1000) {
            System.out.println("Department Manager approves the reimbursement.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(amount);
        }
    }
}

public class FinanceManager extends Handler {
    public void handleRequest(double amount) {
        if (amount > 1000) {
            System.out.println("Finance Manager approves the reimbursement.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(amount);
        }
    }
}

 最后,我们创建一个责任链并定义处理请求的顺序:

public class ReimbursementApproval {
    private Handler approvalChain;

    public ReimbursementApproval() {
        // 创建处理者对象
        Handler employee = new Employee();
        Handler supervisor = new Supervisor();
        Handler departmentManager = new DepartmentManager();
        Handler financeManager = new FinanceManager();

        // 设置处理者之间的顺序
        employee.setNextHandler(supervisor);
        supervisor.setNextHandler(departmentManager);
        departmentManager.setNextHandler(financeManager);

        // 设置责任链的入口
        approvalChain = employee;
    }

    public void processRequest(double amount) {
        approvalChain.handleRequest(amount);
    }
}

public class Main {
    public static void main(String[] args) {
        ReimbursementApproval approval = new ReimbursementApproval();
        approval.processRequest(200);  // Employee approves the reimbursement.
        approval.processRequest(600);  // Supervisor approves the reimbursement.
        approval.processRequest(1200); // Finance Manager approves the reimbursement.
        approval.processRequest(5000); // Finance Manager approves the reimbursement.
    }
}

在上面的示例中,我们创建了一个责任链,其中每个具体处理者都可以决定是否自己处理请求或将其传递给下一个处理者。当调用processRequest方法时,请求会从责任链的入口开始向下传递,直到找到合适的处理者处理请求或者到达链的末尾。

通过责任链模式,我们可以动态地添加、删除或调整处理者的顺序,同时实现了请求发送者和接收者的解耦。这样,在报销审批流程中,不同层级的审批者可以根据具体的金额范围来判断是否批准报销,而无需知道下一个处理者是谁。

责任链模式可以应用于各种场景,如请求过滤器、日志记录器、事件处理等。它提供了一种灵活的方式来处理请求,并且可以动态地调整处理者的顺序和个数,以满足不同的需求。

你可能感兴趣的:(Java设计模式详解,责任链模式)