"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Chain of responsibility

Chain of responsibility

Published on 2024-11-08
Browse:699

Chain of responsibility

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

package Patterns.Behavioral.chainOfResponsibility;

public abstract class AbstractLogger{
    /**
     * TRACE 



ConcreteLoggers

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);
    }

}

Main

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");
    }
}

Output:

ErrorLogger:ERROR:log this error message
InfoLogger:INFO:info level log message
DebugLogger: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.
Release Statement This article is reproduced at: https://dev.to/prashantrmishra/chain-of-responsibility-43a4?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3