Chain of Responsibility Design Patterns

As the name suggests, the Chain of Responsibility Pattern creates a chain of receiver objects for a request. This pattern gives the type of request, decoupling the sender and receiver of the request. This type of design pattern is a behavioral pattern.
In this pattern, usually each receiver contains a reference to another receiver. If an object cannot handle the request, it will pass the same request to the next recipient, and so on.

Application examples: 1. "Drumming and Passing Flowers" in Dream of Red Mansions. 2. Event bubbling in JS. 3. The processing of Encoding by Apache Tomcat in JAVA WEB, the interceptor of Struts2, and the Filter of jsp servlet.

The simple implementation code is as follows:
package com.lyc.design;

public class Chain {

private static AbstractLogger getChainOfLoggers() {

AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger (AbstractLogger.INFO);

errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);

return errorLogger;
}

public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();

loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");

/*
* loggerChain.logMessage(AbstractLogger.DEBUG,
* "This is an debug level information.");
*
* loggerChain.logMessage(AbstractLogger.ERROR,
* "This is an error information.");
*/
}
}

abstract class AbstractLogger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;

protected int level;

// 责任链中的下一个元素
protected AbstractLogger nextLogger;

public void setNextLogger(AbstractLogger nextLogger) {
this.nextLogger = nextLogger;
}

public void logMessage(int level, String message) {
if (this.level <= level) {
write(message);
}
if (nextLogger != null) {
nextLogger.logMessage(level, message);
}
}

abstract protected void write(String message);

}

class ConsoleLogger extends AbstractLogger {

public ConsoleLogger(int level) {
this.level = level;
}

@Override
protected void write(String message) {
System.out.println("Standard Console::Logger: " + message);
}
}

class ErrorLogger extends AbstractLogger {

public ErrorLogger(int level) {
this.level = level;
}

@Override
protected void write(String message) {
System.out.println("Error Console::Logger: " + message);
}
}

class FileLogger extends AbstractLogger {

public FileLogger(int level) {
this.level = level;
}

@Override
protected void write(String message) {
System.out.println("File::Logger: " + message);
}
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326611696&siteId=291194637