责任链模式,顾名思义,它是一个链式模型,这种模式给予请求的类型,对请求的发送者和接收者进行解耦。对于这种结构,每个节点可以拆分在链接,所以,这种模式有着较好的灵活性。
众所周知,Android中最常见的责任链模式。现在我们来实现一个简单的责任链模式。 我们写一个抽象类来指定所有的等级划分。
public abstract class AbstractLogger {
public static final int INFO = 1;
public static final int DEBUG = 2;
public static final 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 InfoLogger extends AbstractLogger {
public InfoLogger(int level){
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("InfoLogger: " + message);
}
}
public class ErrorLogger extends AbstractLogger {
public ErrorLogger(int level){
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("ErrorLogger: " + message);
}
}
public class DebugLogger extends AbstractLogger {
public DebugLogger(int level){
this.level = level;
}
@Override
protected void write(String message) {
System.out.println("DebugLogger: " + message);
}
}
现在我们创建一个Demo,在Demo中我们分别指出每个类的下一级是什么。
public class ChainPatternDemo {
private static AbstractLogger getChainOfLoggers(){
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger debugLogger = new DebugLogger(AbstractLogger.DEBUG);
AbstractLogger infoLogger = new InfoLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(debugLogger);
debugLogger.setNextLogger(infoLogger);
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.");
}
}
输出结果如下:
InfoLogger: This is an information.
DebugLogger: This is an debug level information.
InfoLogger: This is an debug level information.
ErrorLogger: This is an error information.
DebugLogger: This is an error information.
InfoLogger: This is an error information.
优点:
缺点: