首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 設計模式:責任鏈模式(Chain of Responsibility)實戰

     編輯:Java 綜合教學

Java 設計模式:責任鏈模式(Chain of Responsibility)實戰

屬於行為型模式。核心思想:將請求的發送者與接收者解耦,多個處理對象形成鏈,請求沿鏈傳遞直到有對象處理為止。

生活原型

差旅報銷審批:員工 → 組長(≤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 鏈等。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved