前言:责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
JAVA语言版责任链模式
创建日志的抽象类:
public 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);
} else {
nextLogger.logMessage(level, message);
}
}
abstract protected void write(String message);
}
创建继承抽象类的实体类:
public class ConsoleLogger extends AbstractLogger {
public ConsoleLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("标准的控制台日志:" + message);
}
}
public class ErrorLogger extends AbstractLogger {
public ErrorLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("错误的控制台日志:" + message);
}
}
public class FileLogger extends AbstractLogger {
public FileLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("文件日志:" + message);
}
}
创建日志处理的责任链类:
public class ChainOfLoggers {
public 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;
}
}
用ChainPatternDemo演示责任链模式:
public class ChainPatternDemo {
public static void main(String[] args) {
AbstractLogger loggerChain = ChainOfLoggers.getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "这个是普通信息日志");
loggerChain.logMessage(AbstractLogger.DEBUG, "这个是个debug日志");
loggerChain.logMessage(AbstractLogger.ERROR, "这个是error日志");
}
}
输出结果:
标准的控制台日志:这个是普通信息日志
文件日志:这个是个debug日志
错误的控制台日志:这个是error日志