定义:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止
使用场景:一连串对象处理一个请求的场景
实现:定义一个请求处理抽象类,包括一个自己的对象,作为后继处理者,定义处理方法包括处理逻辑和交给下一个处理者处理的调用代码
优点:减少请求者与处理者的耦合
代码示例:日志系统,当前级别大于等于日志处理者则记录
public abstract class Logger {
public static int INFO = 1;
public static int DEBUG = 2;
public static int ERROR = 3;
protected Logger logger;
protected int level;
public Logger(int level) {
this.level = level;
}
public Logger getLogger() {
return logger;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
public abstract void log(int level, String message);
}
public class InfoLogger extends Logger {
public InfoLogger(int level) {
super(level);
}
@Override
public void log(int level, String message) {
if (this.level <= level) {
System.out.println("info:"+message);
}
if (this.logger != null) {
this.logger.log(level, message);
}
}
}
public class DebugLogger extends Logger {
public DebugLogger(int level) {
super(level);
}
@Override
public void log(int level, String message) {
if (this.level <= level) {
System.out.println("debug:"+message);
}
if (this.logger != null) {
this.logger.log(level, message);
}
}
}
public class ErrorLogger extends Logger {
public ErrorLogger(int level) {
super(level);
}
@Override
public void log(int level, String message) {
if (this.level <= level) {
System.out.println("error:"+message);
}
if (this.logger != null) {
this.logger.log(level, message);
}
}
}
public class Main {
public static void main(String[] args) {
InfoLogger info = new InfoLogger(Logger.INFO);
DebugLogger debug = new DebugLogger(Logger.DEBUG);
ErrorLogger error = new ErrorLogger(Logger.ERROR);
info.setLogger(debug);
debug.setLogger(error);
System.out.println("debug");
info.log(Logger.DEBUG, "debug级别日志消息");
System.out.println("error");
info.log(Logger.ERROR, "error级别日志消息");
}
}
结果: