婚礼设计方案网站,托里县城乡建设局网站,中山百度首页推广,哈尔滨自助建站网站系统职责链模式#xff08;Chain of Responsibility Pattern#xff09;是一种行为型设计模式#xff0c;用于将请求的发送者和接收者解耦#xff0c;并使多个对象都有机会处理这个请求。在职责链模式中#xff0c;请求沿着一个链传递#xff0c;直到有一个对象处理它为止。 …职责链模式Chain of Responsibility Pattern是一种行为型设计模式用于将请求的发送者和接收者解耦并使多个对象都有机会处理这个请求。在职责链模式中请求沿着一个链传递直到有一个对象处理它为止。
在职责链模式中通常有以下几个角色
抽象处理者Handler定义处理请求的接口并维护一个指向下一个处理者的引用。通常包含一个处理方法用于处理请求或将请求传递给下一个处理者。具体处理者ConcreteHandler实现抽象处理者接口具体处理请求的逻辑。如果自己无法处理请求可以将请求传递给下一个处理者。客户端Client创建职责链并将请求发送给链中的第一个处理者。
下面是一个简单的示例说明职责链模式的工作原理
// 抽象处理者
public abstract class Handler {private Handler nextHandler;public void setNextHandler(Handler nextHandler) {this.nextHandler nextHandler;}public void handleRequest(Request request) {if (canHandle(request)) {processRequest(request);} else if (nextHandler ! null) {nextHandler.handleRequest(request);} else {// 没有处理者能够处理该请求System.out.println(No handler found for the request.);}}protected abstract boolean canHandle(Request request);protected abstract void processRequest(Request request);
}// 具体处理者A
public class ConcreteHandlerA extends Handler {Overrideprotected boolean canHandle(Request request) {// 判断是否能够处理该请求return request.getType().equals(A);}Overrideprotected void processRequest(Request request) {// 处理请求的逻辑System.out.println(ConcreteHandlerA is handling the request.);}
}// 具体处理者B
public class ConcreteHandlerB extends Handler {Overrideprotected boolean canHandle(Request request) {// 判断是否能够处理该请求return request.getType().equals(B);}Overrideprotected void processRequest(Request request) {// 处理请求的逻辑System.out.println(ConcreteHandlerB is handling the request.);}
}// 请求类
public class Request {private String type;public Request(String type) {this.type type;}public String getType() {return type;}
}// 客户端代码
public class Client {public static void main(String[] args) {// 创建处理者Handler handlerA new ConcreteHandlerA();Handler handlerB new ConcreteHandlerB();// 设置处理者的下一个处理者handlerA.setNextHandler(handlerB);// 创建请求Request requestA new Request(A);Request requestB new Request(B);Request requestC new Request(C);// 发送请求handlerA.handleRequest(requestA); // 输出ConcreteHandlerA is handling the request.handlerA.handleRequest(requestB); // 输出ConcreteHandlerB is handling the request.handlerA.handleRequest(requestC); // 输出No handler found for the request.}
}在上面的示例中抽象处理者Handler定义了处理请求的接口并维护了一个指向下一个处理者的引用。具体处理者ConcreteHandlerA和ConcreteHandlerB实现了抽象处理者接口并根据自身的能力判断是否能够处理请求。如果自己无法处理请求就将请求传递给下一个处理者。客户端Client创建职责链并将请求发送给链中的第一个处理者。
在示例中请求类型为A的请求会被ConcreteHandlerA处理请求类型为B的请求会被ConcreteHandlerB处理而请求类型为C的请求没有任何处理者能够处理最终输出No handler found for the request.。
职责链模式的优点是将请求的发送者和接收者解耦增加了系统的灵活性。同时职责链模式也有可能导致请求的处理链过长影响性能因此在使用时需要注意控制链的长度。