①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);//首先小組長先處理請求
}
}