1、AbstractLogger.java
package com.ssm.cts.pattern.chain; 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); } if (nextLogger != null) { nextLogger.logMessage(level, message); } } abstract protected void write(String message); }
2、ConsoleLogger.java
package com.ssm.cts.pattern.chain; public class ConsoleLogger extends AbstractLogger { public ConsoleLogger(int level) { this.level = level; } @Override protected void write(String message) { System.out.println("ConsoleLogger: " + message); } }
3、FileLogger.java
package com.ssm.cts.pattern.chain; public class FileLogger extends AbstractLogger { public FileLogger(int level) { this.level = level; } @Override protected void write(String message) { System.out.println("FileLogger: " + message); } }
4、ErrorLogger.java
package com.ssm.cts.pattern.chain; public class ErrorLogger extends AbstractLogger { public ErrorLogger(int level) { this.level = level; } @Override protected void write(String message) { System.out.println("ErrorLogger: " + message); } }
5、Demo.java
package com.ssm.cts.pattern.chain; public class Demo { 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, "普通信息"); //loggerChain.logMessage(AbstractLogger.DEBUG, "调试信息"); loggerChain.logMessage(AbstractLogger.ERROR, "异常信息"); } }