责任链模式

描述

责任链模式为请求创建了一个接收者对象链,对象链的工作原理是这样的:当发送者发送一条消息给接收者链时,接收者链首会先得到消息并处理,如果链首没有处理功能,那么就会将消息传递到下一个对象,如果这个对象也处理不了,就继续向下穿,以此类推。

有个很简单的例子:假设程序运行结果有三个层级的消息:error、debug和info,把这三个层级串联为一个链error-->debug-->info,首先检测是不是error,如果是,打印error信息,否则传到debug检测,直到检测出来结果。

实例//创建抽象的记录类public abstract class AbstractLogger {   public static int INFO   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);  
}

//扩展了3个该记录类的记录类实体类
public class ConsoleLogger extends AbstractLogger {

   public ConsoleLogger(int level){
      this.level = level;
   }

   @Override
   protected void write(String message) {        
      System.out.println("Standard Console::Logger: " + message);
   }
}

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 FileLogger extends AbstractLogger {

   public FileLogger(int level){
      this.level = level;
   }

   @Override
   protected void write(String message) {        
      System.out.println("File::Logger: " + message);
   }
}

//创建不同类型的记录器。赋予它们不同的错误级别,并在每个记录器中设置下一个记录
//器。每个记录器中的下一个记录器代表的是链的一部分。
public class ChainPatternDemo {
    
   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);
     //注意,返回的是链首的errorLogger
      return errorLogger;    
   }

   public static void main(String[] args) {
      AbstractLogger loggerChain = getChainOfLoggers();

      loggerChain.logMessage(AbstractLogger.INFO, 
         "This is an information.");
    System.out.println();
loggerChain.logMessage(AbstractLogger.DEBUG, "This is an debug level information.");    System.out.println();
loggerChain.logMessage(AbstractLogger.ERROR, "This is an error information."); } }

输出结果:

Standard Console::Logger: This is an information.
File::Logger: This is an debug level information. Standard Console::Logger: This is an debug level information.
Error Console::Logger: This is an error information. File::Logger: This is an error information. Standard Console::Logger: This is an error information.

 

代码来源: 特别感谢 菜鸟教程java设计模式之责任链模式

posted @ 2017-11-29 11:30  K_artorias  阅读(288)  评论(0编辑  收藏  举报