两种实现方式
第一种
java
public interface IBaseTask {
public void doAction(String isTask,IBaseTask iBaseTask);
}
java
public class ChainManager implements IBaseTask{
//工作类的集合
private List<IBaseTask> iBaseTaskList = new ArrayList<>();
public void addTask(IBaseTask iBaseTask){
iBaseTaskList.add(iBaseTask);
}
//下标
private int index = 0;
@Override
public void doAction(String isTask, IBaseTask iBaseTask) {
if(iBaseTaskList.isEmpty()){};
if (index >= iBaseTaskList.size()){
return;
}
//获取对应下标的任务对象
IBaseTask baseTask = iBaseTaskList.get(index);
index ++;
//执行任务
baseTask.doAction(isTask,iBaseTask);
}
}
//创建三个责任链对象
java
public class TaskOne implements IBaseTask{
@Override
public void doAction(String isTask, IBaseTask iBaseTask) {
if ("1".equals(isTask)) {
System.out.println("拦截器1处理了");
}else{
iBaseTask.doAction(isTask,iBaseTask);
}
}
}
java
public class TaskTwo implements IBaseTask{
@Override
public void doAction(String isTask, IBaseTask iBaseTask) {
if ("2".equals(isTask)) {
System.out.println("拦截器2处理了");
}else{
iBaseTask.doAction(isTask,iBaseTask);
}
}
}
java
public class TaskThree implements IBaseTask{
@Override
public void doAction(String isTask, IBaseTask iBaseTask) {
if ("3".equals(isTask)) {
System.out.println("拦截器3处理了");
}else{
iBaseTask.doAction(isTask,iBaseTask);
}
}
}
执行
java
private void zerenlian1() {
ChainManager chainManager = new ChainManager();
chainManager.addTask(new TaskOne());
chainManager.addTask(new TaskTwo());
chainManager.addTask(new TaskThree());
//从TaskOne开始执行不对的话就自动执行TaskTwo
chainManager.doAction("2",chainManager);
//返回结果 "拦截器2处理了"
}
第二种
java
public abstract class BaseTask {
private boolean isTask;
public BaseTask(boolean isTask) {
this.isTask = isTask;
}
private BaseTask nextTask;
public void addTask(BaseTask nextTask){
this.nextTask = nextTask;
}
public abstract void doAction();
public void action(){
if(isTask){
doAction();
}else{
if(nextTask != null){
nextTask.action();
}
}
}
}
java
public class Task1 extends BaseTask{
public Task1(boolean isTask) {
super(isTask);
}
@Override
public void doAction() {
System.out.println("节点1已被执行");
}
}
java
private void zerenlian() {
Task1 task1 = new Task1(false);
Task2 task2 = new Task2(false);
Task3 task3 = new Task3(true);
task1.addTask(task2);
task2.addTask(task3);
task1.action();
}