责任链模式

Posted by Laiaike on 2022-11-20

责任链模式

责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链,通常每个接收者都包含对另一个接收者的引用,请求沿着这条链进行处理。

  • 应用实例:jsp servlet 的 Filter,JAVA WEB 中 Apache Tomcat 对 Encoding 的处理,JS 中的事件冒泡。

实现

  1. 创建抽象类AbstractLogger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class AbstractLogger {
public static final Integer ERROR_LEVEL = 3;
public static final Integer DEBUG_LEVEL = 2;
public static final Integer INFO_LEVEL = 1;

protected Integer level;
protected AbstractLogger nextAbstractLogger;

public void setNextAbstractLogger(AbstractLogger nextAbstractLogger) {
this.nextAbstractLogger = nextAbstractLogger;
}

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

public void write(String message) {

}
}
  1. 创建三种不同等级的日志实体类,扩展AbstractLogger
1
2
3
4
5
6
7
8
9
10
11
public class ErrorLogger extends AbstractLogger{

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

@Override
public void write(String message) {
System.out.println("ErrorLogger:" + message);
}
}
1
2
3
4
5
6
7
8
9
10
11
public class DebugLogger extends AbstractLogger{

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

@Override
public void write(String message) {
System.out.println("DebugLogger:" + message);
}
}
1
2
3
4
5
6
7
8
9
10
11
public class InfoLogger extends AbstractLogger{

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

@Override
public void write(String message) {
System.out.println("InfoLogger:" + message);
}
}
  1. 创建不同级别的Logger,并指定每个Logger的下一个Logger。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers() {
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR_LEVEL);
AbstractLogger debugLogger = new DebugLogger(AbstractLogger.DEBUG_LEVEL);
AbstractLogger infoLogger = new InfoLogger(AbstractLogger.INFO_LEVEL);

errorLogger.setNextAbstractLogger(debugLogger);
debugLogger.setNextAbstractLogger(infoLogger);

return errorLogger;
}

public static void main(String[] args) {
AbstractLogger chainOfLoggers = getChainOfLoggers();
chainOfLoggers.logMessage(AbstractLogger.ERROR_LEVEL, "This is a log.");
chainOfLoggers.logMessage(AbstractLogger.DEBUG_LEVEL, "This is a log.");
chainOfLoggers.logMessage(AbstractLogger.INFO_LEVEL, "This is a log.");
}
}

结果

1
2
3
4
5
6
ErrorLogger:This is a log.
DebugLogger:This is a log.
InfoLogger:This is a log.
DebugLogger:This is a log.
InfoLogger:This is a log.
InfoLogger:This is a log.