- 抽象责任链处理者
public abstract class AbstractHandler {
//处理级别常量定义
public static final int HANDLE_LEVEL_FIRST = 0;
public static final int HANDLE_LEVEL_SECOND = 1;
//责任链下一级别
private AbstractHandler nextHandler;
//设置责任链下一级别
public void setNextHandler(AbstractHandler nextHandler) {
this.nextHandler = nextHandler;
}
//具体处理,本函数返回为void,可以返回具体处理结果
public final void handle(AbstractRequest request) {
if (request.getRequestLevel() == getHandleLevel()) {
//当前处理级别
this.response(request);
} else if (nextHandler != null) {
//下一处级别
this.nextHandler.handle(request);
} else {
//没有能够处理级别
Log.d("handler", "没有应答");
}
}
//当前级别处理级别
protected abstract int getHandleLevel();
//当前级别响应
protected abstract void response(AbstractRequest request);
}
- 抽象责任链处理者实现类
public class FirstHandler extends AbstractHandler {
@Override
protected int getHandleLevel() {
return AbstractHandler.HANDLE_LEVEL_FIRST;
}
@Override
protected void response(AbstractRequest request) {
//当前级别具体业务处理
Log.d("handler", request.getRequest());
Log.d("handler", "FirstHandler处理结果");
}
}
public class SecondHandler extends AbstractHandler {
@Override
protected int getHandleLevel() {
return AbstractHandler.HANDLE_LEVEL_SECOND;
}
@Override
protected void response(AbstractRequest request) {
//当前级别具体业务处理
Log.d("handler", request.getRequest());
Log.d("handler", "SecondHandler处理结果");
}
}
- 请求抽象类或接口
public abstract class AbstractRequest {
//请求级别
protected abstract int getRequestLevel();
//获取请求内容
protected abstract String getRequest();
}
- 请求抽象类或接口实现类
public class ConcreteRequest extends AbstractRequest {
@Override
protected int getRequestLevel() {
return AbstractHandler.HANDLE_LEVEL_FIRST;
}
@Override
protected String getRequest() {
return "请求内容";
}
}
- 场景使用
//责任链角色
AbstractHandler firstHandler = new FirstHandler();
AbstractHandler secondHandler = new SecondHandler();
//请求
AbstractRequest request = new ConcreteRequest();
//组装责任链
firstHandler.setNextHandler(secondHandler);
//提交请求
firstHandler.handle(request);