屬於行為型模式。核心思想:將請求的發送者與接收者解耦,多個處理對象形成鏈,請求沿鏈傳遞直到有對象處理為止。
差旅報銷審批:員工 → 組長(≤1000) → 總監(≤5000) → 經理(≤10000) → CEO(無上限)。員工只找組長,不關心最終誰批。
public abstract class Leader {
protected Leader nextHandler; // 上級
public final void handlerRequest(int money) {
if (money <= limit()) {
handler(money); // 自己處理
} else if (nextHandler != null) {
nextHandler.handlerRequest(money); // 轉交上級
}
}
public abstract int limit(); // 權限額度
public abstract void handler(int money); // 具體處理
}
public class GroupLeader extends Leader {
public int limit() { return 1000; }
public void handler(int m) { System.out.println("小組長批復了" + m); }
}
public class Director extends Leader {
public int limit() { return 5000; }
public void handler(int m) { System.out.println("主管批復了" + m); }
}
public class Manager extends Leader {
public int limit() { return 10000; }
public void handler(int m) { System.out.println("經理批復了" + m); }
}
public class CEO extends Leader {
public int limit() { return Integer.MAX_VALUE; }
public void handler(int m) { System.out.println("CEO批復了" + m); }
}
public class XiaoZhang {
public static void main(String[] args) {
Leader gl = new GroupLeader();
Leader dr = new Director();
Leader mg = new Manager();
Leader ceo = new CEO();
gl.nextHandler = dr;
dr.nextHandler = mg;
mg.nextHandler = ceo;
gl.handlerRequest(50000); // CEO批復
gl.handlerRequest(500); // 組長批復
gl.handlerRequest(5000); // 主管批復
}
}
CEO批復了50000 小組長批復了500 主管批復了5000
審批流程、異常處理鏈、日誌過濾鏈、Servlet Filter 鏈等。