责任链模式
内容参考 w3cschool
分类:行为型设计模式
应用:HTTP拦截器实现(AOP底层原理)
解释:设置三个等级的人物,前台-》经理-》老板,你想告诉老板一件事,你可以直接发送邮箱告诉老板;可以发送给经理,经理收到了会发送给老板;发送给前台,前台发送给经理,经理再发送给老板。老板每一件事都知道,前台和经理不一定每件事都知道。
目录
UML类图
创建日志输出的抽象类
public abstract class AbstractLogger {
public static final int INFO = 1;
public static final int DEBUG = 2;
public static final 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);
}
}
/**
* 写入
* @param message 消息
*/
abstract protected void write(String message);
}
创建三个级别的日志实例
ConsoleLogger [INFO]
public class ConsoleLogger extends AbstractLogger{
public ConsoleLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("[INFO] console-Logger:"+message);
}
}
DebufLogger [Debug]
public class DebugLogger extends AbstractLogger{
public DebugLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("[Debug] console-Logger:"+message);
}
}
ErrorLogger [Error]
public class ErrorLogger extends AbstractLogger{
public ErrorLogger(int level) {
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("[ERROR] console-Logger:"+message);
}
}
测试运行
public class ExecuteMain {
public static void main(String[] args) {
AbstractLogger loggerChain = getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO,"INFO Level Information");
System.out.println();
loggerChain.logMessage(AbstractLogger.DEBUG,"DEBUG Level Information");
System.out.println();
loggerChain.logMessage(AbstractLogger.ERROR,"ERROR Level Information");
}
private static AbstractLogger getChainOfLoggers(){
AbstractLogger error = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger debug = new DebugLogger(AbstractLogger.DEBUG);
AbstractLogger info = new ConsoleLogger(AbstractLogger.INFO);
error.setNextLogger(debug);
debug.setNextLogger(info);
return error;
}
}
[INFO] console-Logger:INFO Level Information
[Debug] console-Logger:DEBUG Level Information
[INFO] console-Logger:DEBUG Level Information
[ERROR] console-Logger:ERROR Level Information
[Debug] console-Logger:ERROR Level Information
[INFO] console-Logger:ERROR Level Information
Process finished with exit code 0