解耦: 發送者和接收者之間沒有硬連接
靈活性: 可以根據業務需求靈活地添加或刪除處理單元
高可擴展性: 高度模組化,易於維護和擴展,新的處理邏輯可以輕易地被添加到系統中
效能: 可能降低,特別是在長鏈中
請求失效: 中間任一 Handler 發生錯誤,都有可能導致整條鍊的操作失效 (Some requests may end up unhandled)
Debug較不易: 筆者的主觀經驗...,需要很細心的一層層卡斷點來執行,遇到有時效限制,會 Timeout 的場景就會看得很累...
Handler: 定義了一個接口,用於處理請求
ConcreteHandler: 實現Handler接口,並進行實際的請求處理
Client: 發送請求
註: 筆者以前曾在銀行做過軟體工程師,其實金融類應用特別適合使用責任鍊模式哦!
// Handler
class LoanApprover {
public:
LoanApprover* nextApprover;
virtual void setNext(LoanApprover* next) {
nextApprover = next;
}
virtual void approveLoan(int amount) = 0;
};
// ConcreteHandler1: BranchManager
class BranchManager : public LoanApprover {
public:
void approveLoan(int amount) {
if (amount <= 50000) {
cout << "Loan approved by Branch Manager" << endl;
} else if (nextApprover != nullptr) {
nextApprover->approveLoan(amount);
}
}
};
// ConcreteHandler2: RegionalManager
class RegionalManager : public LoanApprover {
public:
void approveLoan(int amount) {
if (amount <= 100000) {
cout << "Loan approved by Regional Manager" << endl;
} else if (nextApprover != nullptr) {
nextApprover->approveLoan(amount);
}
}
};
// Client
int main() {
LoanApprover* branchManager = new BranchManager();
LoanApprover* regionalManager = new RegionalManager();
// 分行經理批准完貸款,下一位換給區經理過目
branchManager->setNext(regionalManager);
int loanAmount = 60000;
// 第一關開始啟動,接下來會一連串的 Handler 處理後續求
branchManager->approveLoan(loanAmount);
}