首頁  >  文章  >  Java  >  責任鏈

責任鏈

DDD
DDD原創
2024-09-18 15:47:02906瀏覽

Chain of responsibility

顧名思義,責任鏈會建立一系列接收者物件來處理請求。
此模式根據請求類型將請求的發送者和接收者解耦。
該模式屬於行為模式。

在此模式中,請求的每個接收者物件都有對下一個物件的引用,如果它無法處理該請求,則該請求將傳遞到鏈中的下一個接收者。

讓我們透過一個日誌機制的範例來理解這一點,該機制根據訊息(請求)的層級來記錄訊息

抽象記錄器

package Patterns.Behavioral.chainOfResponsibility;

public abstract class AbstractLogger{
    /**
     * 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 priority
    public static int DEBUG = 1;
    public static int INFO = 2;
    public static int ERROR = 3;
    protected int LEVEL;
    //next Logger in the chain of responsibility
    private AbstractLogger nextLogger;
    public void setNextLogger(AbstractLogger logger){
        this.nextLogger = logger;
    }
    public void logMessage(int level, String message){
        //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 ERROR
        if(this.LEVEL <=level){
            write(message);
        }
        // else the message/request will be passed down to the next logger/object in the chain
        else{
            if(nextLogger!=null){
                nextLogger.logMessage(level, message);
            }
        }
    }
    abstract void write(String message);
}

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

}

主要

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。

以上是責任鏈的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn