责任链模式
责任链模式
责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。
使用场景: 1、有多个对象可以处理同一个请求,具体哪个对象处理该请求由运行时刻自动确定。 2、在不明确指定接收者的情况下,向多个对象中的一个提交一个请求。 3、可动态指定一组对象处理请求。
1、创建抽象日志类
1 public abstract class AbstractLogger { 2 public static int info = 1; 3 public static int debug = 2; 4 public static int error = 3; 5 6 protected int level; 7 8 protected AbstractLogger nextLogger; 9 10 public void setNextLogger(AbstractLogger abstractLogger) { 11 this.nextLogger = abstractLogger; 12 } 13 14 public void logMessage(int level,String Message){ 15 if(this.level<= level){ 16 write(Message); 17 } 18 if(nextLogger != null){ 19 nextLogger.logMessage(level,Message); 20 } 21 } 22 23 protected abstract void write(String Message); 24 }
2、创建扩展了该抽象日志类的实体类
1 public class ConsoleLogger extends AbstractLogger { 2 public ConsoleLogger(int level){ 3 this.level = level; 4 } 5 @Override 6 protected void write(String Message) { 7 System.out.println("Console log:" + Message); 8 } 9 }
1 public class DebugLogger extends AbstractLogger { 2 public DebugLogger(int level){ 3 this.level = level; 4 } 5 @Override 6 protected void write(String Message) { 7 System.out.println("Debug log:"+ Message); 8 } 9 }
1 public class ErrorLogger extends AbstractLogger { 2 public ErrorLogger(int level){ 3 this.level = level; 4 } 5 6 @Override 7 protected void write(String Message) { 8 System.out.println("Error logger:"+Message); 9 } 10 }
3、测试类
1 public class ChainPatternDemo { 2 public static void main(String[] args) { 3 AbstractLogger loggerChain = getChainLogger(); 4 loggerChain.logMessage(AbstractLogger.info,"This is an information."); 5 loggerChain.logMessage(AbstractLogger.debug,"This is debug information."); 6 loggerChain.logMessage(AbstractLogger.error,"This is error information."); 7 } 8 9 private static AbstractLogger getChainLogger() { 10 AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.info); 11 AbstractLogger debugLogger = new DebugLogger(AbstractLogger.debug); 12 AbstractLogger errorLogger = new ErrorLogger(ErrorLogger.error); 13 14 errorLogger.setNextLogger(debugLogger); 15 debugLogger.setNextLogger(consoleLogger); 16 17 return errorLogger; 18 } 19 }
4、运行状态
当运行loggerChain.logMessage(AbstractLogger.error,"This is error information.")时
5、测试结果
Console log:This is an information.
Debug log:This is debug information.
Console log:This is debug information.
Error logger:This is error information.
Debug log:This is error information.
Console log:This is error information.