责任链
顾名思义,责任链创建一系列接收者对象来处理请求。
该模式根据请求类型将请求的发送者和接收者解耦。
该模式属于行为模式。
在此模式中,请求的每个接收者对象都有对下一个对象的引用,如果它无法处理该请求,则该请求将传递到链中的下一个接收者。
让我们通过一个日志机制的例子来理解这一点,该机制根据消息(请求)的级别来记录消息
抽象记录器
package patterns.behavioral.chainofresponsibility; public abstract class abstractlogger{ /** * trace <p>concreteloggers<br></p>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要点
- 遵循lsp(里氏替换原则,即实体设计模式)。
- 遵循坚实原则的srp。
- 遵循 ocp 的坚实原则,因为我们可以添加更多记录器,如跟踪、致命等,而无需修改现有代码。
- 也遵循 isp。
以上就是责任链的详细内容,更多请关注其它相关文章!