责任链模式 核心设计类 IBaseTask :
public abstract class IBaseTask {
boolean isTask;
IBaseTask iNextTask;
public IBaseTask(boolean isTask){
this.isTask = isTask;
}
public void setNextTask(IBaseTask iNextTask) {
this.iNextTask = iNextTask;
}
public void action() {
if(isTask) {
doAction();
} else if(iNextTask!=null) {
iNextTask.action();
}
}
public abstract void doAction();
}
public class Task1 extends IBaseTask{
public Task1(boolean isTask) {
super(isTask);
}
@Override
public void doAction() {
System.out.println("Task1 执行了");
}
}
public class Task2 extends IBaseTask {
public Task2(boolean isTask) {
super(isTask);
}
@Override
public void doAction() {
System.out.println("Task2 执行了");
}
}
public class Task3 extends IBaseTask {
public Task3(boolean isTask) {
super(isTask);
}
@Override
public void doAction() {
System.out.println("Task3 执行了");
}
}
测试:
public static void main(String[] args) {
Task1 task1 = new Task1(false);
Task2 task2 = new Task2(true);
Task3 task3 = new Task3(true);
task1.setNextTask(task2);
task2.setNextTask(task3);
task1.action();
}
执行结果:
Task2 执行了