①UML设计:
②定义:职责链模式(称责任链模式)将请求的处理对象像一条长链一般组合起来,形成一条对象链。请求并不知道具体执行请求的对象是哪一个,这样就实现了请求与处理对象之间的解耦
③示例:
public abstract class Leader {
private Leader nextLeader;
public abstract void deal(Vocation vocation);
public void setNextLeader(Leader leader) {
this.nextLeader = leader;
}
public Leader getNextLeader() {
return nextLeader;
}
}
/**
* 1天的假期由小组长审批
*/
public class GroupLeader extends Leader {
private final int day = 1;
@Override
public void deal(Vocation vocation) {
if (vocation.getDays() > day) {
getNextLeader().deal(vocation);
} else {
System.out.println("GroupLeader deal the vocation for 1 day");
}
}
}
/**
* 1~3天的假期有部门领导审批
*/
public class DepartmentLeader extends Leader {
private final int days = 3;
@Override
public void deal(Vocation vocation) {
if (vocation.getDays() > days) {
getNextLeader().deal(vocation);
} else {
System.out.println("Department deal the vocation for more than 1-3 days");
}
}
}
/**
* 3天以上的假期由主管审批
*/
public class GeneralLeader extends Leader {
@Override
public void deal(Vocation vocation) {
System.out.println("GeneralLeader deal the vocation no matter how many days");
}
}
public class Vocation {
private int days;
private String reasons;
public void setDays(int days) {
this.days = days;
}
public int getDays() {
return days;
}
public void setReasons(String reasons) {
this.reasons = reasons;
}
public String getReasons() {
return reasons;
}
}
public class Client3 {
public static void main(String[] args) {
Vocation vocation = new Vocation();
vocation.setDays(4);//设置不同的请假天数,不同的领导人会处理
Leader gpLeader = new GroupLeader();
Leader dmLeader = new DepartmentLeader();
Leader gLeader = new GeneralLeader();
gpLeader.setNextLeader(dmLeader);
dmLeader.setNextLeader(gLeader);
gpLeader.deal(vocation);//首先小组长先处理请求
}
}