责任链模式

1.责任链模式简介

责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者
进行解耦。属于行为型模式。
在这种模式中,通常每个接收者都包含对另一个接收者的引用,构成一个单向链表。如果一个对象不能处理该请求,那么它会把相同的请求传
给下一个接收者,依此类推。
可以避免请求发送者与接收者耦合在一起,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递。让多个对象都有
可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。

 

2.试验Demo

abstract class Logger {
    public static int DEBUG = 1;
    public static int INFO = 2;
    public static int ERROR = 3;

    protected int level;
    protected Logger nextLogger;

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

    public void setNext(Logger nextLogger) {
        this.nextLogger = nextLogger;
    }

    public void print(int level, String message) {
        if (level <= this.level) {
            write(message);    
        } else {
            if (nextLogger != null) {
                nextLogger.print(level, message);
            }
        }
    }

    abstract public void write(String message);
}


class DebugLogger extends Logger {
    public DebugLogger(int level) {
        super(level);
    }
    public void write(String message) {
        System.out.println("DebugLogger: " + message);
    }
}


class InfoLogger extends Logger {
    public InfoLogger(int level) {
        super(level);
    }
    public void write(String message) {
        System.out.println("InfoLogger: " + message);
    }
}


class ErrorLogger extends Logger {
    public ErrorLogger(int level) {
        super(level);
    }
    public void write(String message) {
        System.out.println("ErrorLogger: " + message);
    }
}



public class ChainPatternDemo {
    public static void main(String args[]) {
        Logger logger = createLoggerChain();

        logger.print(Logger.DEBUG, "This is a debug message");
        logger.print(Logger.INFO, "This is a info message");
        logger.print(Logger.ERROR, "This is a error message");
    }


    public static Logger createLoggerChain() {
        Logger debug = new DebugLogger(Logger.DEBUG);
        Logger info = new InfoLogger(Logger.INFO);
        Logger error = new ErrorLogger(Logger.ERROR);
    
        debug.setNext(info);
        info.setNext(error);

        return debug;
    }
}

 

 

参考:https://i.cnblogs.com/EditPosts.aspx?opt=1

 

posted on 2019-04-16 22:58  Hello-World3  阅读(125)  评论(0编辑  收藏  举报

导航