- 抽象处理者
- AbstractLog
- 具体处理者
- DebugLog
- InfoLog
- ErrorLog
- 测试
责任链模式属于行为型模式
责任链模式中,处理者持有对下家的引用,
形成一条链,请求在这个链上传递,直到某一个处理者处理此请求,
或者不处理一直到责任链结束。
责任链可能是一条线,也可能是一条环链。
包含有抽象处理者、具体处理者两种角色。
我们以不同级别的日志打印为例
抽象处理者 AbstractLogpackage com.example.duohoob.dp.responsibilitychain;
public abstract class AbstractLog {
protected int level;
protected AbstractLog nextLog;
public void setNextLog(AbstractLog nextLog) {
this.nextLog = nextLog;
}
public abstract void logMessage(String message);
public void handlerRequest(int level, String message) {
if (!(level > this.level)) {
// 可以处理,不大于当前日志级别
logMessage(message);
} else {
// 不能处理,看是否有下一处理者
if (null != nextLog) {
nextLog.handlerRequest(level, message);
}
}
}
}
具体处理者
DebugLog
package com.example.duohoob.dp.responsibilitychain;
public class DebugLog extends AbstractLog {
public DebugLog() {
level = 1;
}
@Override
public void logMessage(String message) {
// TODO Auto-generated method stub
System.out.println("DebugLog打印***" + message);
}
}
InfoLog
package com.example.duohoob.dp.responsibilitychain;
public class InfoLog extends AbstractLog {
public InfoLog() {
level = 2;
}
@Override
public void logMessage(String message) {
// TODO Auto-generated method stub
System.out.println("InfoLog打印***" + message);
}
}
ErrorLog
package com.example.duohoob.dp.responsibilitychain;
public class ErrorLog extends AbstractLog {
public ErrorLog() {
level = 3;
}
@Override
public void logMessage(String message) {
// TODO Auto-generated method stub
System.out.println("ErrorLog打印***" + message);
}
}
测试
package com.example.duohoob.dp.responsibilitychain;
public class LogTest {
public static AbstractLog getChain() {
AbstractLog debugLog = new DebugLog();
AbstractLog infoLog = new InfoLog();
debugLog.setNextLog(infoLog);
AbstractLog errorLog = new ErrorLog();
infoLog.setNextLog(errorLog);
return debugLog;
}
public static void main(String[] args) {
AbstractLog abstractLog = getChain();
abstractLog.handlerRequest(1, "debug级别的日志");
abstractLog.handlerRequest(2, "info级别的日志");
abstractLog.handlerRequest(3, "error级别的日志");
}
}
运行



