责任链模式属于行为型模式
责任链模式中,处理者持有对下家的引用,
形成一条链,请求在这个链上传递,直到某一个处理者处理此请求,
或者不处理一直到责任链结束。
责任链可能是一条线,也可能是一条环链。
包含有抽象处理者、具体处理者两种角色。
我们以不同级别的日志打印为例
抽象处理者
AbstractLog
package com.example.duohoob.dp.responsibilitychain;
/**
* 抽象处理者
* @Title: AbstractLog.java
* @Package com.example.duohoob.dp.responsibilitychain
*
* @author yangwei
* @date 2022年7月12日
*/
public abstract class AbstractLog {
/**
* 日志级别:1debug、2info、3error
*/
protected int level;
/**
* 责任链中的下一个处理者
*/
protected AbstractLog nextLog;
public void setNextLog(AbstractLog nextLog) {
this.nextLog = nextLog;
}
/**
* 打印日志
* @author yangwei
* @date 2022年7月12日
*
* @param message
*/
public abstract void logMessage(String message);
/**
* 处理请求
* @author yangwei
* @date 2022年7月12日
*
*/
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;
/**
* 具体处理者DebugLog
* @Title: DebugLog.java
* @Package com.example.duohoob.dp.responsibilitychain
*
* @author yangwei
* @date 2022年7月12日
*/
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;
/**
* 具体处理者InfoLog
* @Title: InfoLog.java
* @Package com.example.duohoob.dp.responsibilitychain
*
* @author yangwei
* @date 2022年7月12日
*/
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;
/**
* 具体处理者ErrorLog
* @Title: ErrorLog.java
* @Package com.example.duohoob.dp.responsibilitychain
*
* @author yangwei
* @date 2022年7月12日
*/
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;
/**
* 测试
* @Title: LogTest.java
* @Package com.example.duohoob.dp.responsibilitychain
*
* @author yangwei
* @date 2022年7月12日
*/
public class LogTest {
/**
* 获取责任链
* 按日志级别从小到大排列,各持有大一级日志处理者的引用
* 这样就得到了一个责任链,然后返回日志级别最小的处理者
* @author yangwei
* @date 2022年7月12日
*
* @return
*/
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级别的日志");
}
}
运行