顾名思义,责任链创建了一系列接收者对象来处理请求。
该模式根据请求类型将请求的发送者和接收者解耦。
该模式属于行为模式。
在此模式中,请求的每个接收者对象都有一个对下一个对象的引用,如果它无法处理该请求,则该请求将被传递到链中的下一个接收者。
让我们以基于消息(请求)级别记录消息的日志记录机制为例来理解这一点
AbstractLogger
package Patterns.Behavioral.chainOfResponsibility; public abstract class AbstractLogger{ /** * TRACEConcreteLoggers
package Patterns.Behavioral.chainOfResponsibility; public class DebugLogger extends AbstractLogger { private String className = this.getClass().getSimpleName(); private String logger = "DEBUG"; public DebugLogger(){ this.LEVEL = 1; } @Override void write(String message) { System.out.println(className ":" logger ":" message); } } package Patterns.Behavioral.chainOfResponsibility; public class InfoLogger extends AbstractLogger { private String className = this.getClass().getSimpleName(); private String logger = "INFO"; public InfoLogger(){ this.LEVEL = 2; } @Override void write(String message) { System.out.println(className ":" logger ":" message); } } package Patterns.Behavioral.chainOfResponsibility; public class ErrorLogger extends AbstractLogger { private String className = this.getClass().getSimpleName(); private String logger = "ERROR"; public ErrorLogger(){ this.LEVEL = 3; } @Override void write(String message) { System.out.println(className ":" logger ":" message); } }主要的
package Patterns.Behavioral.chainOfResponsibility; public class Main { public static AbstractLogger intializeLoggers(){ AbstractLogger errorLogger = new ErrorLogger(); //LEVEL = 3; AbstractLogger infoLogger = new InfoLogger(); //LEVEL = 2; AbstractLogger debugLogger = new DebugLogger(); // LEVEL = 1; errorLogger.setNextLogger(infoLogger); infoLogger.setNextLogger(debugLogger); return errorLogger;// return the highest priority Logger first } public static void main(String args[]){ // initialize the chain of responsible objects AbstractLogger logger = intializeLoggers(); //pass the request down the responsibility chain //logging level 3 logger logger.logMessage(3, "log this error message"); //loggin level 2 logger logger.logMessage(2, "info level log message"); //logging level 1 logger logger.logMessage(1, "debug level log message"); } }输出:
ErrorLogger:ERROR:log this error message InfoLogger:INFO:info level log message DebugLogger:DEBUG:debug level log message要点
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3