设计模式之责任链的学习思考

来源:互联网 发布:热血屠龙翅膀进阶数据 编辑:程序博客网 时间:2024/06/12 20:19

责任链模式,顾名思义,每个对象之间形成一条链,这条链形成的基础是各级对象的责任;当一个消息请求发来时,依次传递,哪个对象符合消息处理的条件就处理。
这个模式可以让消息的发送者不清楚消息的处理者具体是谁,职责链将请求的发送者和请求的处理者解耦了。属于设计模式里的行为型模式

设计:

  • 一个抽象类,属性有各级指数,后继对象,方法有抽象和非抽象:非抽象是判断谁处理,抽象是各级对象具体处理方法;
  • 各实现抽象类的具体类
  • public实现类

小例子:

abstract class AbstractLogger{    public static int INFO=1;    public static int DEBUG=2;    public static int ERROR=3;    int level;      //责任链上的各级指数    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);//各级责任对象的独有处理方法}class ConsoleLogger extends AbstractLogger{    public ConsoleLogger(int level){        this.level=level;    }    protected void write(String message) {        System.out.println("ConsoleLogger:"+message);    }}class ErrorLogger extends AbstractLogger{    public ErrorLogger(int level){        this.level=level;    }    protected void write(String message) {        System.out.println("ErrorLogger:"+message);    }}class FileLogger extends AbstractLogger{    public FileLogger(int level){        this.level=level;    }    protected void write(String message) {        System.out.println("FileLogger:"+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);        return errorLogger;    }    public static void main(String[] args) {        AbstractLogger loggerChain=getChainOfLoggers();        loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");        loggerChain.logMessage(AbstractLogger.DEBUG, "This is an debug level information.");        loggerChain.logMessage(AbstractLogger.ERROR, "This is an error information.");    }}

输出:

    ConsoleLogger:This is an information.    FileLogger:This is an debug level information.    ConsoleLogger:This is an debug level information.    ErrorLogger:This is an error information.    FileLogger:This is an error information.    ConsoleLogger:This is an error information.
原创粉丝点击