Now, let us understand the chain of responsibility pattern with an example. The given below UML diagram will make you easily understand.
[Source]
So here we have three different logger class which extends the main abstract logger class and a client class.
Each class has its attributes and methods like Logger has output info, error info, debug info as attributes, and set Logger, Message, display Log Info as methods.
Console Based Logger class has a console-based logger and displays Log Info as methods but no attributes of its own. Debug Based Logger has Debug Based Logger(int levels) and displays Log Info as methods but no attributes of it
The client class which is Chain of Responsibility Client has de chain() and main methods.
Main logger class
public abstract class Logger {
public static int OUTPUTINFO = 1;
public static int ERRORINFO = 2;
public static int DEBUGINFO = 3;
protected int levels;
protected Logger nextLevelLogger;
public void setNextLevelLogger( Logger nextLevelLogger )
{
this.nextLevelLogger = nextLevelLogger;
}
public void logMessage( int levels, String msg )
{
if(this.levels <= levels){
displayLogInfo(msg);
}
if (nextLevelLogger != null) {
nextLevelLogger.logMessage(levels, msg);
}
}
protected abstract void displayLogInfo(String msg);
}
Console based logger class
public class DebugBasedLogger extends Logger {
public DebugBasedLogger(int levels) {
this.levels = levels;
}
@Override
protected void displayLogInfo(String msg) {
System.out.println("DEBUG LOGGER INFO: " + msg);
}
}
Error based logger class
public class ErrorBasedLogger extends Logger {
public ErrorBasedLogger(int levels) {
this.levels=levels;
}
@Override
protected void displayLogInfo(String msg) {
System.out.println("ERROR LOGGER INFO: " + msg);
}
}
Client class / main class
public class ChainofResponsibilityClient {
private static Logger doChaining(){
Logger consoleLogger = new ConsoleBasedLogger(Logger.OUTPUTINFO);
Logger errorLogger = new ErrorBasedLogger(Logger.ERRORINFO);
consoleLogger.setNextLevelLogger(errorLogger);
Logger debugLogger = new DebugBasedLogger(Logger.DEBUGINFO);
errorLogger.setNextLevelLogger(debugLogger);
return consoleLogger;
}
public static void main(String args[]){
Logger chainLogger = doChaining();
chainLogger.logMessage(Logger.OUTPUTINFO, "Enter the sequence of values ");
chainLogger.logMessage(Logger.ERRORINFO, "An error has occurred now");
chainLogger.logMessage(Logger.DEBUGINFO, "This was the error now debugging is compiled");
}
}
Output:
AbilityClient
CONSOLE LOGGER INFO: Enter the sequence of values
CONSOLE LOGGER INFO: An error has occurred now
ERROR LOGGER INFO: An error has occurred now
CONSOLE LOGGER INFO: This was the error now debugging is compiled
ERROR LOGGER INFO: This was the error now debugging is compiled
DEBUG LOGGER INFO: This was the error now debugging is compiled