10.20

责任链模式

责任链模式(Chain of Responsibility Pattern)是一种行为型设计模式,它将请求的发送者和接收者解耦,使多个对象都有机会处理这个请求。每个接收者都包含对下一个接收者的引用,形成一个链条,请求沿着这个链条依次传递,直到有一个接收者处理它。

下面是一个简单的Java代码示例,演示了责任链模式的实现:

// 请求类
class Request {
    private String content;

    public Request(String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}

// 处理者接口
interface Handler {
    void setNext(Handler nextHandler);
    void handleRequest(Request request);
}

// 具体处理者A
class ConcreteHandlerA implements Handler {
    private Handler nextHandler;

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

    public void handleRequest(Request request) {
        if (request.getContent().equals("A")) {
            System.out.println("ConcreteHandlerA handles the request.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

// 具体处理者B
class ConcreteHandlerB implements Handler {
    private Handler nextHandler;

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

    public void handleRequest(Request request) {
        if (request.getContent().equals("B")) {
            System.out.println("ConcreteHandlerB handles the request.");
        } else if (nextHandler != null) {
            nextHandler.handleRequest(request);
        }
    }
}

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

        handlerA.setNext(handlerB);

        Request request1 = new Request("A");
        handlerA.handleRequest(request1);

        Request request2 = new Request("B");
        handlerA.handleRequest(request2);

        Request request3 = new Request("C");
        handlerA.handleRequest(request3);
    }
}
 
posted @ 2024-11-20 10:17  liuxuechao  阅读(1)  评论(0编辑  收藏  举报