As the name suggests, a chain of responsibility creates a chain of receiver objects to handle requests.
This pattern decouples the request's sender and receiver based on the request type.
This pattern comes under the Behavioural pattern.
In this pattern each receiver object of the request has a reference to the next object if it can not handle the request, the request is passed down to the next receiver in the chain.
Let's understand this by taking the example of a logging mechanism that logs messages based on the level of the message (request)
AbstractLogger
packagePatterns.Behavioral.chainOfResponsibility;publicabstractclassAbstractLogger{/** * TRACE < DEBUG < INFO < WARN < ERROR < FATAL * which means if the level is INFO, then INFO, WARN, ERROR and FATAL messages will be logged * but if the level is ERROR then only ERROR and FATAL messages will be logged *///higher the number higher the prioritypublicstaticintDEBUG=1;publicstaticintINFO=2;publicstaticintERROR=3;protectedintLEVEL;//next Logger in the chain of responsibilityprivateAbstractLoggernextLogger;publicvoidsetNextLogger(AbstractLoggerlogger){this.nextLogger=logger;}publicvoidlogMessage(intlevel,Stringmessage){//If the logging level of the message is greater than the current Logger's LEVEL then it will be logged//example if level = ERROR and this.LEVEL = INFO then the message will be logged as INFO has a lower priority than ERRORif(this.LEVEL<=level){write(message);}// else the message/request will be passed down to the next logger/object in the chainelse{if(nextLogger!=null){nextLogger.logMessage(level,message);}}}abstractvoidwrite(Stringmessage);}
ConcreteLoggers
packagePatterns.Behavioral.chainOfResponsibility;publicclassDebugLoggerextendsAbstractLogger{privateStringclassName=this.getClass().getSimpleName();privateStringlogger="DEBUG";publicDebugLogger(){this.LEVEL=1;}@Overridevoidwrite(Stringmessage){System.out.println(className+":"+logger+":"+message);}}packagePatterns.Behavioral.chainOfResponsibility;publicclassInfoLoggerextendsAbstractLogger{privateStringclassName=this.getClass().getSimpleName();privateStringlogger="INFO";publicInfoLogger(){this.LEVEL=2;}@Overridevoidwrite(Stringmessage){System.out.println(className+":"+logger+":"+message);}}packagePatterns.Behavioral.chainOfResponsibility;publicclassErrorLoggerextendsAbstractLogger{privateStringclassName=this.getClass().getSimpleName();privateStringlogger="ERROR";publicErrorLogger(){this.LEVEL=3;}@Overridevoidwrite(Stringmessage){System.out.println(className+":"+logger+":"+message);}}
Main
packagePatterns.Behavioral.chainOfResponsibility;publicclassMain{publicstaticAbstractLoggerintializeLoggers(){AbstractLoggererrorLogger=newErrorLogger();//LEVEL = 3;AbstractLoggerinfoLogger=newInfoLogger();//LEVEL = 2;AbstractLoggerdebugLogger=newDebugLogger();// LEVEL = 1;errorLogger.setNextLogger(infoLogger);infoLogger.setNextLogger(debugLogger);returnerrorLogger;// return the highest priority Logger first}publicstaticvoidmain(Stringargs[]){// initialize the chain of responsible objectsAbstractLoggerlogger=intializeLoggers();//pass the request down the responsibility chain//logging level 3 loggerlogger.logMessage(3,"log this error message");//loggin level 2 loggerlogger.logMessage(2,"info level log message");//logging level 1 loggerlogger.logMessage(1,"debug level log message");}}
Output:
ErrorLogger:ERROR:log this error messageInfoLogger:INFO:info level log messageDebugLogger:DEBUG:debug level log message
Key points
- Follows LSP (The Liskov substitution principle i.e. solid design pattern).
- Follows SRP of solid principle.
- Follows OCP of solid principle as we can add more Loggers like trace, fatal, etc without modifying existing code at all.
- Follows ISP as well.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse